<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved
#    $Jesús Ventosinos Mayor <jesus@pexego.es>$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, orm
from openerp import api

class sale_order(orm.Model):

    _inherit = 'sale.order'

    _columns = {
        'state': fields.selection([
            ('draft', 'Draft Quotation'),
            ('sent', 'Quotation Sent'),
            ('cancel', 'Cancelled'),
            ('reserve', 'Reserved'),
            ('waiting_date', 'Waiting Schedule'),
            ('wait_risk', 'Waiting Risk Approval'),
            ('risk_approval', 'Risk & VIES approval'),
            ('progress', 'Sales Order'),
            ('manual', 'Sale to Invoice'),
            ('shipping_except', 'Shipping Exception'),
            ('invoice_except', 'Invoice Exception'),
            ('done', 'Done'),
            ], 'Status', readonly=True, copy=False, help="Gives the status of the quotation or sales order.\
              \nThe exception status is automatically set when a cancel operation occurs \
              in the invoice validation (Invoice Exception) or in the picking list process (Shipping Exception).\nThe 'Waiting Schedule' status is set when the invoice is confirmed\
               but waiting for the scheduler to run on the order date.", select=True),
    }

    def action_risk_approval(self, cr, uid, ids, context=None):
        order = self.browse(cr, uid, ids[0], context)
        view_form = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'sale_custom', 'sale_confirm_wizard_form_wizard')
        wzd = self.pool('sale.confirm.wizard').create(cr, uid, {})
        import ipdb
        ipdb.set_trace()
        if not order.is_all_reserved and 'confirmed' not in context:
            return {'name': "Sale confirm",
                    'view_mode': 'form',
                    'view_type': 'form',
                    'res_model': 'sale.confirm.wizard',
                    'type': 'ir.actions.act_window',
                    'target': 'new',
                    'res_id': wzd,
                    'views': [(view_form[1], 'form')]
                    }
        else:
            self.apply_promotions(cr, uid, ids, context)
            self.write(cr, uid, ids, {'state': 'risk_approval'}, context)

            self.action_button_confirm(cr, uid, ids, context)
            return True
<commit_msg>[FIX] 'partner_risk__stock_reserve__rel': PEP8 indentation<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2014 Pexego Sistemas Informáticos All Rights Reserved
#    $Jesús Ventosinos Mayor <jesus@pexego.es>$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp.osv import fields, orm
from openerp import api

class sale_order(orm.Model):

    _inherit = 'sale.order'

    _columns = {
        'state': fields.selection([
            ('draft', 'Draft Quotation'),
            ('sent', 'Quotation Sent'),
            ('cancel', 'Cancelled'),
            ('reserve', 'Reserved'),
            ('waiting_date', 'Waiting Schedule'),
            ('wait_risk', 'Waiting Risk Approval'),
            ('risk_approval', 'Risk & VIES approval'),
            ('progress', 'Sales Order'),
            ('manual', 'Sale to Invoice'),
            ('shipping_except', 'Shipping Exception'),
            ('invoice_except', 'Invoice Exception'),
            ('done', 'Done'),
            ], 'Status', readonly=True, copy=False, help="Gives the status of the quotation or sales order.\
              \nThe exception status is automatically set when a cancel operation occurs \
              in the invoice validation (Invoice Exception) or in the picking list process (Shipping Exception).\nThe 'Waiting Schedule' status is set when the invoice is confirmed\
               but waiting for the scheduler to run on the order date.", select=True),
    }

    def action_risk_approval(self, cr, uid, ids, context=None):
        order = self.browse(cr, uid, ids[0], context)
        view_form = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'sale_custom', 'sale_confirm_wizard_form_wizard')
        wzd = self.pool('sale.confirm.wizard').create(cr, uid, {})
        import ipdb
        ipdb.set_trace()
        if not order.is_all_reserved and 'confirmed' not in context:
            return {'name': "Sale confirm",
                    'view_mode': 'form',
                    'view_type': 'form',
                    'res_model': 'sale.confirm.wizard',
                    'type': 'ir.actions.act_window',
                    'target': 'new',
                    'res_id': wzd,
                    'views': [(view_form[1], 'form')]
                    }
        else:
            self.apply_promotions(cr, uid, ids, context)
            self.write(cr, uid, ids, {'state': 'risk_approval'}, context)

            self.action_button_confirm(cr, uid, ids, context)
            return True
<|endoftext|>


<commit_before>from wpc import db, app, socketio
from wpc.models import MozillaStreamHack  # NOQA
from wpc.models import YoutubeStream, Stream, Streamer, Subscriber, get_or_create, WPCStream
from wpc.forms import SubscribeForm, EditStreamerInfoForm, SearchForm

from flask import render_template, request, redirect, url_for, flash, jsonify, g, Response, session
from flask.ext.login import login_user, logout_user, login_required, current_user
from jinja2 import escape, evalcontextfilter, Markup
from flask.ext.socketio import emit

from uuid import uuid4
import praw
from crossdomain import crossdomain
import random
from feedgen.feed import FeedGenerator
from datetime import datetime
import pytz

@app.before_request
def add_ga_tracking_code():
    g.ga_tracking_code = app.config['GA_TRACKING_CODE']

@app.before_request
def create_search_form():
    g.search_form = SearchForm()

def url_for_other_page(page):
    args = request.view_args.copy()
    args['page'] = page
    return url_for(request.endpoint, **args)

app.jinja_env.globals['url_for_other_page'] = url_for_other_page

@app.route('/', methods=['GET', 'POST'])
def index():
    wpc_stream = Stream.query.filter_by(type='wpc_stream', status='live').first()
    live_streams = Stream.query.filter_by(status='live').order_by(Stream.actual_start_time.desc().nullslast(), Stream.id.desc()).all()
    # Uncomment this when mozilla guys start livestreaming
    # live_streams.insert(0, MozillaStreamHack())

    form = SubscribeForm()
    if request.method == "POST" and form.validate_on_submit():
        subscriber = Subscriber()
        form.populate_obj(subscriber)
        db.session.add(subscriber)
        db.session.commit()
        flash("you've subscribed successfully", "success")
        return redirect(url_for('.index'))

    random_stream = YoutubeStream.query.filter(YoutubeStream.status != 'upcoming').order_by(db.func.random()).first()
    upcoming_streams = Stream.query.filter_by(status='upcoming').order_by(Stream.scheduled_start_time.asc()).all()
    return render_template('index.html', form=form, live_streams=live_streams,
                           random_stream=random_stream,
                           upcoming_streams=upcoming_streams, wpc_stream=wpc_stream)

# TODO it is copypasted from index(), but whatever, this is one time change
@app.route('/onlineconf', methods=['GET', 'POST'])
def onlineconf():
    streams = Stream.query.filter_by(confstream=True).filter(Stream.status == 'completed').order_by(Stream.actual_start_time.desc().nullslast(), Stream.id.desc()).all()

    form = SubscribeForm()
    if request.method == "POST" and form.validate_on_submit():
        subscriber = Subscriber()
        form.populate_obj(subscriber)
        db.session.add(subscriber)
        db.session.commit()
        flash("you've subscribed successfully", "success")
        return redirect(url_for('.index'))

    return render_template('onlineconf.html', form=form, streams=streams)

@app.route('/search', methods=['GET', 'POST'])
def search():
    if g.search_form.validate_on_submit():
        return redirect(url_for("past_streams", query=g.search_form.query.data))
    else:
        # Should never happen, unless user requested /search manually
        return redirect(url_for("past_streams"))

@app.route('/past_streams', defaults={'page': 1, 'query': None}, methods=["GET", "POST"])
@app.route('/past_streams/query/<query>', defaults={'page': 1}, methods=["GET", "POST"])
@app.route('/past_streams/page/<int:page>', defaults={'query': None}, methods=["GET", "POST"])
@app.route('/past_streams/query/<query>/page/<int:page>', methods=["GET", "POST"])
def past_streams(query, page):
    streams = YoutubeStream.query.filter_by(status='completed')

    if query:
        terms = [t.strip() for t in query.split(" ")]
        streams = streams.filter(YoutubeStream.title.match(" & ".join(terms)))

    streams = streams.order_by(YoutubeStream.scheduled_start_time.desc().nullslast()).paginate(page, per_page=5)
    return render_template('past_streams.html', streams=streams, page=page, query=query)

@app.route('/streamers/', defaults={'page': 1})
@app.route('/streamers/<int:page>')
def streamers_list(page):
    streamers = Streamer.query.filter(Streamer.streams.any()).order_by(Streamer.reddit_username).paginate(page, per_page=50)
    return render_template('streamers_list.html', streamers=streamers)

@app.template_filter()
@evalcontextfilter
def nl2br(eval_ctx, value):
    result = (u'%s' % escape(value)).replace('\n', '
')
    if eval_ctx.autoescape:
        result = Markup(result)
    return result

def nl2br_py(value):
    result = (u'%s' % escape(value)).replace('\n', '
')
    return result

@app.route('/streamer/<streamer_name>', defaults={'page': 1}, methods=["GET", "POST"])
@app.route('/streamer/<streamer_name>/<int:page>', methods=["GET", "POST"])
def streamer_page(streamer_name, page):
    streamer = Streamer.query.filter_by(reddit_username=streamer_name).first()
    streams = streamer.streams.order_by(Stream.scheduled_start_time.desc().nullslast()).paginate(page, per_page=5)
    form = EditStreamerInfoForm()

    if current_user.is_authenticated() and current_user == streamer:
        if request.method == 'POST':
            if form.validate_on_submit():
                current_user.populate(form)
                db.session.commit()
                flash("Updated successfully", category='success')
                return redirect(url_for('.streamer_page', streamer_name=streamer_name))
            else:
                return render_template('streamer.html', streamer=streamer, streams=streams, form=form, edit=True)
        else:
            form.youtube_channel.data = current_user.youtube_channel
            form.twitch_channel.data = current_user.twitch_channel
            form.info.data = current_user.info

    return render_template('streamer.html', streamer=streamer, streams=streams, form=form, edit=False)

@app.route('/json')
@crossdomain(origin='*', max_age=15)
def stream_json():
    def make_dict(stream):
        return {'username': stream.streamer.reddit_username if stream.streamer else None,
                'title': stream.title, 'url': stream.normal_url(), 'viewers': stream.current_viewers}
    try:
        return jsonify(live=[make_dict(st) for st in Stream.query.filter_by(status='live')],
                       upcoming=[make_dict(st) for st in Stream.query.filter_by(status='upcoming')],
                       completed=[make_dict(st) for st in YoutubeStream.query.filter_by(status='completed')])
    except Exception as e:
        app.logger.exception(e)
        return jsonify(error=True)

@app.route('/reddit_authorize_callback')
def reddit_authorize_callback():
    r = praw.Reddit(user_agent=app.config["REDDIT_WEB_APP_USER_AGENT"])
    r.set_oauth_app_info(app.config['REDDIT_API_ID'], app.config['REDDIT_API_SECRET'], url_for('.reddit_authorize_callback', _external=True))
    if str(session['unique_key']) == request.args.get('state', ''):
        code = request.args.get('code', '')
        if code:
            r.get_access_information(code)
            name = r.get_me().name
            if name:
                user = get_or_create(Streamer, reddit_username=name)
                user.checked = True
                db.session.commit()
                login_user(user)
                flash("Logged in successfully", 'success')
                return redirect(url_for(".streamer_page", streamer_name=name))

    flash("Error while trying to log in", 'error')
    return redirect(url_for(".index"))

@app.route('/auth')
def authorize():
    r = praw.Reddit(user_agent=app.config["REDDIT_WEB_APP_USER_AGENT"])
    r.set_oauth_app_info(app.config['REDDIT_API_ID'], app.config['REDDIT_API_SECRET'], url_for('.reddit_authorize_callback', _external=True))
    session['unique_key'] = uuid4()
    url = r.get_authorize_url(session['unique_key'], 'identity')
    return redirect(url)

@app.route("/logout")
@login_required
def logout():
    logout_user()
    flash("Logged out successfully", 'info')
    return redirect(url_for(".index"))

@app.route("/podcast_feed.xml")
def podcast_feed():
    logo_url = url_for("static", filename="wpclogo_big.png", _external=True)

    fg = FeedGenerator()
    fg.load_extension('podcast')
    fg.podcast.itunes_category('Technology', 'Podcasting')
    fg.podcast.itunes_image(logo_url)
    fg.author({'name': 'Nathan Kellert', 'email': 'nathankellert@gmail.com'})
    fg.link(href='http://watchpeoplecode.com/podcast_feed.xml', rel='self')
    fg.title('WPC Coders Podcast')
    fg.description('WPC Coders Podcast is a weekly peek into the lives of developers and the WatchPeopleCode community. Our goal is to keep our listeners entertained by giving them new and interesting insights into our industry as well as awesome things happening within our own community. Here, you can expect hear about some of the latest news, tools, and opportunities for developers in nearly every aread of our industry. Most importantly, we hope to have some fun and a few laughs in ways only other nerds know how.')  # NOQA

    episodes = [('ep1.mp3', 'Episode 1', datetime(2015, 02, 21, 23), 'Learn all about the WPC hosts, and where we came from in Episode 1!'),
                ('ep2.mp3', 'Episode 2', datetime(2015, 02, 28, 23), 'This week we cover your news, topics and questions in episode 2!'),
                ('ep3.mp3', 'Episode 3', datetime(2015, 03, 07, 23), "On todays podcast we talk to WatchPeopleCode's founder Alex Putilin. Hear about how the reddit search engine thousands watched him write. Also, hear the inside scoop of how WatchPeopleCode got started!"),  # NOQA
                ('ep4.mp3', 'Episode 4', datetime(2015, 03, 14, 23), "This week we talk to FreeCodeCamps Quincy Larson(http://www.freecodecamp.com) about their project that combines teaching new developers how to code and completing projects for non-profits! Lets find out how this group of streamers code with a cause!")]  # NOQA

    for epfile, eptitle, epdate, epdescription in episodes[::-1]:
        epurl = "https://s3.amazonaws.com/wpcpodcast/{}".format(epfile)
        fe = fg.add_entry()
        fe.id(epurl)
        fe.title(eptitle)
        fe.description(epdescription)
        fe.podcast.itunes_image(logo_url)
        fe.pubdate(epdate.replace(tzinfo=pytz.UTC))
        fe.enclosure(epurl, 0, 'audio/mpeg')

    return Response(response=fg.rss_str(pretty=True),
                    status=200,
                    mimetype='application/rss+xml')

@app.route("/no_lag_alpha_test")
def streams():
    return render_template("streams.html", wpc_stream=WPCStream.query.first())

users = list()
first_words = ['True', 'False', 'For', 'While', 'If', 'Else', 'Elif', 'Undefined', 'Do',
               'Exit', 'Continue', 'Super', 'Break', 'Try', 'Catch', 'Class', 'Object',
               'Def', 'Var', 'Pass', 'Return']
second_words = ['C', 'C++', 'Lisp', 'Python', 'Java', 'JavaScript', 'Pascal', 'Objective-C',
                'C#', 'Perl', 'Ruby', 'Ada', 'Haskell', 'Octave', 'Basic', 'Fortran']

@socketio.on('connect', namespace='/chat')
def chat_connect():
    print('New connection')

    if current_user.is_authenticated():
        session['username'] = current_user.reddit_username
    elif 'username' not in session or session['username'] in users:
        while True:
            session['username'] = random.choice(first_words) + ' ' + random.choice(second_words)
            if session['username'] not in users:
                break

    users.append(session['username'])
    emit('join', True, session['username'])

@socketio.on('disconnect', namespace='/chat')
def chat_disconnect():
    users.remove(session['username'])

@socketio.on('message', namespace='/chat')
def chat_message(message_text):
    message = {"sender": session['username'],
               "text": nl2br_py(message_text)}
    emit("message", message, broadcast=True)
    return True
<commit_msg>order streams on streamer's page by actual start time<commit_after>from wpc import db, app, socketio
from wpc.models import MozillaStreamHack  # NOQA
from wpc.models import YoutubeStream, Stream, Streamer, Subscriber, get_or_create, WPCStream
from wpc.forms import SubscribeForm, EditStreamerInfoForm, SearchForm

from flask import render_template, request, redirect, url_for, flash, jsonify, g, Response, session
from flask.ext.login import login_user, logout_user, login_required, current_user
from jinja2 import escape, evalcontextfilter, Markup
from flask.ext.socketio import emit

from uuid import uuid4
import praw
from crossdomain import crossdomain
import random
from feedgen.feed import FeedGenerator
from datetime import datetime
import pytz

@app.before_request
def add_ga_tracking_code():
    g.ga_tracking_code = app.config['GA_TRACKING_CODE']

@app.before_request
def create_search_form():
    g.search_form = SearchForm()

def url_for_other_page(page):
    args = request.view_args.copy()
    args['page'] = page
    return url_for(request.endpoint, **args)

app.jinja_env.globals['url_for_other_page'] = url_for_other_page

@app.route('/', methods=['GET', 'POST'])
def index():
    wpc_stream = Stream.query.filter_by(type='wpc_stream', status='live').first()
    live_streams = Stream.query.filter_by(status='live').order_by(Stream.actual_start_time.desc().nullslast(), Stream.id.desc()).all()
    # Uncomment this when mozilla guys start livestreaming
    # live_streams.insert(0, MozillaStreamHack())

    form = SubscribeForm()
    if request.method == "POST" and form.validate_on_submit():
        subscriber = Subscriber()
        form.populate_obj(subscriber)
        db.session.add(subscriber)
        db.session.commit()
        flash("you've subscribed successfully", "success")
        return redirect(url_for('.index'))

    random_stream = YoutubeStream.query.filter(YoutubeStream.status != 'upcoming').order_by(db.func.random()).first()
    upcoming_streams = Stream.query.filter_by(status='upcoming').order_by(Stream.scheduled_start_time.asc()).all()
    return render_template('index.html', form=form, live_streams=live_streams,
                           random_stream=random_stream,
                           upcoming_streams=upcoming_streams, wpc_stream=wpc_stream)

# TODO it is copypasted from index(), but whatever, this is one time change
@app.route('/onlineconf', methods=['GET', 'POST'])
def onlineconf():
    streams = Stream.query.filter_by(confstream=True).filter(Stream.status == 'completed').order_by(Stream.actual_start_time.desc().nullslast(), Stream.id.desc()).all()

    form = SubscribeForm()
    if request.method == "POST" and form.validate_on_submit():
        subscriber = Subscriber()
        form.populate_obj(subscriber)
        db.session.add(subscriber)
        db.session.commit()
        flash("you've subscribed successfully", "success")
        return redirect(url_for('.index'))

    return render_template('onlineconf.html', form=form, streams=streams)

@app.route('/search', methods=['GET', 'POST'])
def search():
    if g.search_form.validate_on_submit():
        return redirect(url_for("past_streams", query=g.search_form.query.data))
    else:
        # Should never happen, unless user requested /search manually
        return redirect(url_for("past_streams"))

@app.route('/past_streams', defaults={'page': 1, 'query': None}, methods=["GET", "POST"])
@app.route('/past_streams/query/<query>', defaults={'page': 1}, methods=["GET", "POST"])
@app.route('/past_streams/page/<int:page>', defaults={'query': None}, methods=["GET", "POST"])
@app.route('/past_streams/query/<query>/page/<int:page>', methods=["GET", "POST"])
def past_streams(query, page):
    streams = YoutubeStream.query.filter_by(status='completed')

    if query:
        terms = [t.strip() for t in query.split(" ")]
        streams = streams.filter(YoutubeStream.title.match(" & ".join(terms)))

    streams = streams.order_by(YoutubeStream.scheduled_start_time.desc().nullslast()).paginate(page, per_page=5)
    return render_template('past_streams.html', streams=streams, page=page, query=query)

@app.route('/streamers/', defaults={'page': 1})
@app.route('/streamers/<int:page>')
def streamers_list(page):
    streamers = Streamer.query.filter(Streamer.streams.any()).order_by(Streamer.reddit_username).paginate(page, per_page=50)
    return render_template('streamers_list.html', streamers=streamers)

@app.template_filter()
@evalcontextfilter
def nl2br(eval_ctx, value):
    result = (u'%s' % escape(value)).replace('\n', '
')
    if eval_ctx.autoescape:
        result = Markup(result)
    return result

def nl2br_py(value):
    result = (u'%s' % escape(value)).replace('\n', '
')
    return result

@app.route('/streamer/<streamer_name>', defaults={'page': 1}, methods=["GET", "POST"])
@app.route('/streamer/<streamer_name>/<int:page>', methods=["GET", "POST"])
def streamer_page(streamer_name, page):
    streamer = Streamer.query.filter_by(reddit_username=streamer_name).first()
    streams = streamer.streams.order_by(Stream.actual_start_time.desc().nullslast()).paginate(page, per_page=5)
    form = EditStreamerInfoForm()

    if current_user.is_authenticated() and current_user == streamer:
        if request.method == 'POST':
            if form.validate_on_submit():
                current_user.populate(form)
                db.session.commit()
                flash("Updated successfully", category='success')
                return redirect(url_for('.streamer_page', streamer_name=streamer_name))
            else:
                return render_template('streamer.html', streamer=streamer, streams=streams, form=form, edit=True)
        else:
            form.youtube_channel.data = current_user.youtube_channel
            form.twitch_channel.data = current_user.twitch_channel
            form.info.data = current_user.info

    return render_template('streamer.html', streamer=streamer, streams=streams, form=form, edit=False)

@app.route('/json')
@crossdomain(origin='*', max_age=15)
def stream_json():
    def make_dict(stream):
        return {'username': stream.streamer.reddit_username if stream.streamer else None,
                'title': stream.title, 'url': stream.normal_url(), 'viewers': stream.current_viewers}
    try:
        return jsonify(live=[make_dict(st) for st in Stream.query.filter_by(status='live')],
                       upcoming=[make_dict(st) for st in Stream.query.filter_by(status='upcoming')],
                       completed=[make_dict(st) for st in YoutubeStream.query.filter_by(status='completed')])
    except Exception as e:
        app.logger.exception(e)
        return jsonify(error=True)

@app.route('/reddit_authorize_callback')
def reddit_authorize_callback():
    r = praw.Reddit(user_agent=app.config["REDDIT_WEB_APP_USER_AGENT"])
    r.set_oauth_app_info(app.config['REDDIT_API_ID'], app.config['REDDIT_API_SECRET'], url_for('.reddit_authorize_callback', _external=True))
    if str(session['unique_key']) == request.args.get('state', ''):
        code = request.args.get('code', '')
        if code:
            r.get_access_information(code)
            name = r.get_me().name
            if name:
                user = get_or_create(Streamer, reddit_username=name)
                user.checked = True
                db.session.commit()
                login_user(user)
                flash("Logged in successfully", 'success')
                return redirect(url_for(".streamer_page", streamer_name=name))

    flash("Error while trying to log in", 'error')
    return redirect(url_for(".index"))

@app.route('/auth')
def authorize():
    r = praw.Reddit(user_agent=app.config["REDDIT_WEB_APP_USER_AGENT"])
    r.set_oauth_app_info(app.config['REDDIT_API_ID'], app.config['REDDIT_API_SECRET'], url_for('.reddit_authorize_callback', _external=True))
    session['unique_key'] = uuid4()
    url = r.get_authorize_url(session['unique_key'], 'identity')
    return redirect(url)

@app.route("/logout")
@login_required
def logout():
    logout_user()
    flash("Logged out successfully", 'info')
    return redirect(url_for(".index"))

@app.route("/podcast_feed.xml")
def podcast_feed():
    logo_url = url_for("static", filename="wpclogo_big.png", _external=True)

    fg = FeedGenerator()
    fg.load_extension('podcast')
    fg.podcast.itunes_category('Technology', 'Podcasting')
    fg.podcast.itunes_image(logo_url)
    fg.author({'name': 'Nathan Kellert', 'email': 'nathankellert@gmail.com'})
    fg.link(href='http://watchpeoplecode.com/podcast_feed.xml', rel='self')
    fg.title('WPC Coders Podcast')
    fg.description('WPC Coders Podcast is a weekly peek into the lives of developers and the WatchPeopleCode community. Our goal is to keep our listeners entertained by giving them new and interesting insights into our industry as well as awesome things happening within our own community. Here, you can expect hear about some of the latest news, tools, and opportunities for developers in nearly every aread of our industry. Most importantly, we hope to have some fun and a few laughs in ways only other nerds know how.')  # NOQA

    episodes = [('ep1.mp3', 'Episode 1', datetime(2015, 02, 21, 23), 'Learn all about the WPC hosts, and where we came from in Episode 1!'),
                ('ep2.mp3', 'Episode 2', datetime(2015, 02, 28, 23), 'This week we cover your news, topics and questions in episode 2!'),
                ('ep3.mp3', 'Episode 3', datetime(2015, 03, 07, 23), "On todays podcast we talk to WatchPeopleCode's founder Alex Putilin. Hear about how the reddit search engine thousands watched him write. Also, hear the inside scoop of how WatchPeopleCode got started!"),  # NOQA
                ('ep4.mp3', 'Episode 4', datetime(2015, 03, 14, 23), "This week we talk to FreeCodeCamps Quincy Larson(http://www.freecodecamp.com) about their project that combines teaching new developers how to code and completing projects for non-profits! Lets find out how this group of streamers code with a cause!")]  # NOQA

    for epfile, eptitle, epdate, epdescription in episodes[::-1]:
        epurl = "https://s3.amazonaws.com/wpcpodcast/{}".format(epfile)
        fe = fg.add_entry()
        fe.id(epurl)
        fe.title(eptitle)
        fe.description(epdescription)
        fe.podcast.itunes_image(logo_url)
        fe.pubdate(epdate.replace(tzinfo=pytz.UTC))
        fe.enclosure(epurl, 0, 'audio/mpeg')

    return Response(response=fg.rss_str(pretty=True),
                    status=200,
                    mimetype='application/rss+xml')

@app.route("/no_lag_alpha_test")
def streams():
    return render_template("streams.html", wpc_stream=WPCStream.query.first())

users = list()
first_words = ['True', 'False', 'For', 'While', 'If', 'Else', 'Elif', 'Undefined', 'Do',
               'Exit', 'Continue', 'Super', 'Break', 'Try', 'Catch', 'Class', 'Object',
               'Def', 'Var', 'Pass', 'Return']
second_words = ['C', 'C++', 'Lisp', 'Python', 'Java', 'JavaScript', 'Pascal', 'Objective-C',
                'C#', 'Perl', 'Ruby', 'Ada', 'Haskell', 'Octave', 'Basic', 'Fortran']

@socketio.on('connect', namespace='/chat')
def chat_connect():
    print('New connection')

    if current_user.is_authenticated():
        session['username'] = current_user.reddit_username
    elif 'username' not in session or session['username'] in users:
        while True:
            session['username'] = random.choice(first_words) + ' ' + random.choice(second_words)
            if session['username'] not in users:
                break

    users.append(session['username'])
    emit('join', True, session['username'])

@socketio.on('disconnect', namespace='/chat')
def chat_disconnect():
    users.remove(session['username'])

@socketio.on('message', namespace='/chat')
def chat_message(message_text):
    message = {"sender": session['username'],
               "text": nl2br_py(message_text)}
    emit("message", message, broadcast=True)
    return True
<|endoftext|>


<commit_before>#!/usr/bin/env python
# Matthews_coef.py
#   Copyright (C) 2006 CCLRC, Graeme Winter
#
#   This code is distributed under the terms and conditions of the
#   CCP4 Program Suite Licence Agreement as a CCP4 Library.
#   A copy of the CCP4 licence can be obtained by writing to the
#   CCP4 Secretary, Daresbury Laboratory, Warrington WA4 4AD, UK.
#
# 5th June 2006
#
# An example of an matthews_coef CCP4 program wrapper, which can be used
# as the base for other wrappers.
#
# Provides:
#
# Solvent contents given a number of molecules, a sequence length and a unit
# cell and symmetry.

import os
import sys

if not os.environ.has_key('XIA2CORE_ROOT'):
    raise RuntimeError, 'XIA2CORE_ROOT not defined'

if not os.path.join(os.environ['XIA2CORE_ROOT'],
                    'Python') in sys.path:
    sys.path.append(os.path.join(os.environ['XIA2CORE_ROOT'],
                                 'Python'))

from Driver.DriverFactory import DriverFactory
from Decorators.DecoratorFactory import DecoratorFactory

def Matthews_coef(DriverType = None):
    '''A factory for Matthews_coefWrapper classes.'''

    DriverInstance = DriverFactory.Driver(DriverType)
    CCP4DriverInstance = DecoratorFactory.Decorate(DriverInstance, 'ccp4')

    class Matthews_coefWrapper(CCP4DriverInstance.__class__):
        '''A wrapper for Matthews_coef, using the CCP4-ified Driver.'''

        def __init__(self):
            # generic things
            CCP4DriverInstance.__class__.__init__(self)
            self.set_executable('matthews_coef')

            self._nmol = 1
            self._nres = 0
            self._cell = None
            self._symmetry = None

            # results

            self._solvent = 0.0

            return

        # setters follow

        def set_nmol(self, nmol):
            self._nmol = nmol
            return

        def set_nres(self, nres):
            self._nres = nres
            return

        def set_cell(self, cell):
            self._cell = cell
            return

        def set_symmetry(self, symmetry):
            self._symmetry = symmetry
            return

        def compute_solvent(self):

            self.start()

            self.input('cell %f %f %f %f %f %f' % tuple(self._cell))
            self.input('symmetry %s' % self._symmetry)
            self.input('nres %d' % self._nres)
            self.input('nmol %d' % self._nmol)

            self.close_wait()

            self.check_for_errors()
            self.check_ccp4_errors()

            # get the useful information out from here...

            for line in self.get_all_output():
                if 'Assuming protein density' in line:
                    self._solvent = 0.01 * float(line.split()[-1])

            return

        def get_solvent(self):
            return self._solvent

    return Matthews_coefWrapper()

if __name__ == '__main__':

    # then run a test!

    m = Matthews_coef()

    m.set_symmetry('P43212')
    m.set_cell((96.0, 96.0, 36.75, 90.0, 90.0, 90.0))
    m.set_nmol(2)
    m.set_nres(82)

    m.compute_solvent()

    print m.get_solvent()

<commit_msg>symmetry -> spacegroup<commit_after>#!/usr/bin/env python
# Matthews_coef.py
#   Copyright (C) 2006 CCLRC, Graeme Winter
#
#   This code is distributed under the terms and conditions of the
#   CCP4 Program Suite Licence Agreement as a CCP4 Library.
#   A copy of the CCP4 licence can be obtained by writing to the
#   CCP4 Secretary, Daresbury Laboratory, Warrington WA4 4AD, UK.
#
# 5th June 2006
#
# An example of an matthews_coef CCP4 program wrapper, which can be used
# as the base for other wrappers.
#
# Provides:
#
# Solvent contents given a number of molecules, a sequence length and a unit
# cell and symmetry.

import os
import sys

if not os.environ.has_key('XIA2CORE_ROOT'):
    raise RuntimeError, 'XIA2CORE_ROOT not defined'

if not os.path.join(os.environ['XIA2CORE_ROOT'],
                    'Python') in sys.path:
    sys.path.append(os.path.join(os.environ['XIA2CORE_ROOT'],
                                 'Python'))

from Driver.DriverFactory import DriverFactory
from Decorators.DecoratorFactory import DecoratorFactory

def Matthews_coef(DriverType = None):
    '''A factory for Matthews_coefWrapper classes.'''

    DriverInstance = DriverFactory.Driver(DriverType)
    CCP4DriverInstance = DecoratorFactory.Decorate(DriverInstance, 'ccp4')

    class Matthews_coefWrapper(CCP4DriverInstance.__class__):
        '''A wrapper for Matthews_coef, using the CCP4-ified Driver.'''

        def __init__(self):
            # generic things
            CCP4DriverInstance.__class__.__init__(self)
            self.set_executable('matthews_coef')

            self._nmol = 1
            self._nres = 0
            self._cell = None
            self._spacegroup = None

            # results

            self._solvent = 0.0

            return

        # setters follow

        def set_nmol(self, nmol):
            self._nmol = nmol
            return

        def set_nres(self, nres):
            self._nres = nres
            return

        def set_cell(self, cell):
            self._cell = cell
            return

        def set_spacegroup(self, spacegroup):
            self._spacegroup = spacegroup
            return

        def compute_solvent(self):

            self.start()

            self.input('cell %f %f %f %f %f %f' % tuple(self._cell))

            # cannot cope with spaces in the spacegroup!

            self.input('symmetry %s' % self._spacegroup.replace(' ', ''))
            self.input('nres %d' % self._nres)
            self.input('nmol %d' % self._nmol)

            self.close_wait()

            self.check_for_errors()
            self.check_ccp4_errors()

            # get the useful information out from here...

            for line in self.get_all_output():
                if 'Assuming protein density' in line:
                    self._solvent = 0.01 * float(line.split()[-1])

            return

        def get_solvent(self):
            return self._solvent

    return Matthews_coefWrapper()

if __name__ == '__main__':

    # then run a test!

    m = Matthews_coef()

    m.set_spacegroup('P43212')
    m.set_cell((96.0, 96.0, 36.75, 90.0, 90.0, 90.0))
    m.set_nmol(2)
    m.set_nres(82)

    m.compute_solvent()

    print m.get_solvent()

<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2014 Pexego All Rights Reserved
#    $Jesús Ventosinos Mayor <jesus@pexego.es>$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

{
    'name': "Purchase product category",
    'version': '1.0',
    'category': 'product',
    'description': """Adds a new category to the product.""",
    'author': 'Pexego',
    'website': 'www.pexego.es',
    "depends": ['base', 'product', 'account'],
    "data": ['product_view.xml',
             'security/ir.model.access.csv'],
    "installable": True
}
<commit_msg>[FIX]purchase_product_category: Añadida dependencia.<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2014 Pexego All Rights Reserved
#    $Jesús Ventosinos Mayor <jesus@pexego.es>$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

{
    'name': "Purchase product category",
    'version': '1.0',
    'category': 'product',
    'description': """Adds a new category to the product.""",
    'author': 'Pexego',
    'website': 'www.pexego.es',
    "depends": ['base', 'product', 'account', 'purchase'],
    "data": ['product_view.xml',
             'security/ir.model.access.csv'],
    "installable": True
}
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from wagtail.wagtailcore.models import Page

def create_initial_data(apps, schema_editor):
    home_page = Page.objects.get(url_path="/home/")
    ContentType = apps.get_model('contenttypes.ContentType')

    top_level_pages = [
        {'app': 'ocean_stories', 'model_name': 'OceanStories', 'title': 'Ocean Stories', 'content_type': 'oceanstories'},
        {'app': 'calendar', 'model_name': 'Calendar', 'title': 'Calendar', 'content_type': 'calendar'},
        {'app': 'data_gaps', 'model_name': 'DataGaps', 'title': 'Data Gaps', 'content_type': 'datagaps'},
        {'app': 'data_catalog', 'model_name': 'DataCatalog', 'title': 'Data Catalog', 'content_type': 'datacatalog'},
    ]

    for p in top_level_pages:
        model = apps.get_model('%s.%s' % (p['app'], p['model_name']))
        content_type, created = ContentType.objects.get_or_create(
            model=p['content_type'], app_label=p['app'])
        home_page.add_child(instance=model(
            title=p['title'],
            live=False,
            content_type=content_type,
        ))

class Migration(migrations.Migration):

    # dependencies = [
    #     ('ocean_stories', '__latest__'),
    #     ('calendar', '__latest__'),
    #     ('data_gaps', '__latest__'),
    #     ('data_catalog', '__latest__'),
    #     ('home', '__latest__'),
    #
    # ]

    operations = [
        migrations.RunPython(create_initial_data),
    ]
<commit_msg>allow initial data migration to run by listing dependencies<commit_after># -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from wagtail.wagtailcore.models import Page

def create_initial_data(apps, schema_editor):
    home_page = Page.objects.get(url_path="/home/")
    ContentType = apps.get_model('contenttypes.ContentType')

    top_level_pages = [
        {'app': 'ocean_stories', 'model_name': 'OceanStories', 'title': 'Ocean Stories', 'content_type': 'oceanstories'},
        {'app': 'calendar', 'model_name': 'Calendar', 'title': 'Calendar', 'content_type': 'calendar'},
        {'app': 'data_gaps', 'model_name': 'DataGaps', 'title': 'Data Gaps', 'content_type': 'datagaps'},
        {'app': 'data_catalog', 'model_name': 'DataCatalog', 'title': 'Data Catalog', 'content_type': 'datacatalog'},
    ]

    for p in top_level_pages:
        model = apps.get_model('%s.%s' % (p['app'], p['model_name']))
        content_type, created = ContentType.objects.get_or_create(
            model=p['content_type'], app_label=p['app'])
        home_page.add_child(instance=model(
            title=p['title'],
            live=False,
            content_type=content_type,
        ))

class Migration(migrations.Migration):

    dependencies = [
        ('ocean_stories', '0001_initial'),
        ('calendar', '0001_initial'),
        ('data_gaps', '0001_initial'),
        ('data_catalog', '0001_initial'),
        ('home', '0001_initial'),

    ]

    operations = [
        migrations.RunPython(create_initial_data),
    ]
<|endoftext|>


<commit_before>"""
pymdown.smartsymbols
Really simple plugin to add support for
  copyright, trademark, and registered symbols
  plus/minus

MIT license.

Copyright (c) 2014 Isaac Muse <isaacmuse@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import unicode_literals
from markdown import Extension
from markdown.inlinepatterns import HtmlPattern
from markdown.odict import OrderedDict
from markdown.treeprocessors import InlineProcessor

RE_TRADE = ("smart-trademark", r'\(tm\)', r'™')
RE_COPY = ("smart-copyright", r'\(c\)', r'©')
RE_REG = ("smart-registered", r'\(r\)', r'®')
RE_PLUSMINUS = ("smart-plus-minus", r'\+/-', r'±')
RE_DOUBLE_ARROW = ("smart-double-arrow", r'\<(?:-{2}|–)\>', r'↔')
RE_RIGHT_ARROW = ("smart-right-arrow", r'(?:-{2}|–)\>', r'→')
RE_LEFT_ARROW = ("smart-left-arrow", r'\<(?:-{2}|–)', r'←')
RE_NOT_EQUAL = ("smart-not-equal", r'!=', r'≠')

REPL = {
    'trademark': RE_TRADE,
    'copyright': RE_COPY,
    'registered': RE_REG,
    'plusminus': RE_PLUSMINUS,
    'arrows': (RE_LEFT_ARROW, RE_RIGHT_ARROW, RE_DOUBLE_ARROW),
    'notequal': RE_NOT_EQUAL
}

class SmartSymbolsPattern(HtmlPattern):
    def __init__(self, pattern, replace, md):
        """ Setup replace pattern """
        super(SmartSymbolsPattern, self).__init__(pattern)
        self.replace = replace
        self.md = md

    def handleMatch(self, m):
        """ Replace symbol """
        return self.md.htmlStash.store(m.expand(self.replace), safe=True)

class SmartSymbolsExtension(Extension):
    def __init__(self, *args, **kwargs):
        """ Setup config of which symbols are enabled """
        self.config = {
            'trademark': [True, 'Trademark'],
            'copyright': [True, 'Copyright'],
            'registered': [True, 'Registered'],
            'plusminus': [True, 'Plus/Minus'],
            'arrows': [True, 'Arrows'],
            'notequal': [True, 'Not Equal']
        }
        super(SmartSymbolsExtension, self).__init__(*args, **kwargs)

    def add_pattern(self, patterns, md):
        """ Construct the inline symbol pattern """
        self.patterns.add(
            patterns[0],
            SmartSymbolsPattern(patterns[1], patterns[2], md),
            '_begin'
        )

    def extendMarkdown(self, md, md_globals):
        """ Create a dict of inline replace patterns and add to the treeprocessor """
        configs = self.getConfigs()
        self.patterns = OrderedDict()

        for k, v in REPL.items():
            if configs[k]:
                if isinstance(v[0], (list, tuple)):
                    for subv in v:
                        self.add_pattern(subv, md)
                else:
                    self.add_pattern(v, md)

        inlineProcessor = InlineProcessor(md)
        inlineProcessor.inlinePatterns = self.patterns
        md.treeprocessors.add('smart-symbols', inlineProcessor, '_end')
        if "smarty" in md.treeprocessors.keys():
            md.treeprocessors.link('smarty', '_end')

def makeExtension(*args, **kwargs):
    return SmartSymbolsExtension(*args, **kwargs)
<commit_msg>Simplify arrow regex<commit_after>"""
pymdown.smartsymbols
Really simple plugin to add support for
  copyright, trademark, and registered symbols
  plus/minus

MIT license.

Copyright (c) 2014 Isaac Muse <isaacmuse@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from __future__ import unicode_literals
from markdown import Extension
from markdown.inlinepatterns import HtmlPattern
from markdown.odict import OrderedDict
from markdown.treeprocessors import InlineProcessor

RE_TRADE = ("smart-trademark", r'\(tm\)', r'™')
RE_COPY = ("smart-copyright", r'\(c\)', r'©')
RE_REG = ("smart-registered", r'\(r\)', r'®')
RE_PLUSMINUS = ("smart-plus-minus", r'\+/-', r'±')
RE_DOUBLE_ARROW = ("smart-double-arrow", r'\<-{2}\>', r'↔')
RE_RIGHT_ARROW = ("smart-right-arrow", r'-{2}\>', r'→')
RE_LEFT_ARROW = ("smart-left-arrow", r'\<-{2}', r'←')
RE_NOT_EQUAL = ("smart-not-equal", r'!=', r'≠')

REPL = {
    'trademark': RE_TRADE,
    'copyright': RE_COPY,
    'registered': RE_REG,
    'plusminus': RE_PLUSMINUS,
    'arrows': (RE_LEFT_ARROW, RE_RIGHT_ARROW, RE_DOUBLE_ARROW),
    'notequal': RE_NOT_EQUAL
}

class SmartSymbolsPattern(HtmlPattern):
    def __init__(self, pattern, replace, md):
        """ Setup replace pattern """
        super(SmartSymbolsPattern, self).__init__(pattern)
        self.replace = replace
        self.md = md

    def handleMatch(self, m):
        """ Replace symbol """
        return self.md.htmlStash.store(m.expand(self.replace), safe=True)

class SmartSymbolsExtension(Extension):
    def __init__(self, *args, **kwargs):
        """ Setup config of which symbols are enabled """
        self.config = {
            'trademark': [True, 'Trademark'],
            'copyright': [True, 'Copyright'],
            'registered': [True, 'Registered'],
            'plusminus': [True, 'Plus/Minus'],
            'arrows': [True, 'Arrows'],
            'notequal': [True, 'Not Equal']
        }
        super(SmartSymbolsExtension, self).__init__(*args, **kwargs)

    def add_pattern(self, patterns, md):
        """ Construct the inline symbol pattern """
        self.patterns.add(
            patterns[0],
            SmartSymbolsPattern(patterns[1], patterns[2], md),
            '_begin'
        )

    def extendMarkdown(self, md, md_globals):
        """ Create a dict of inline replace patterns and add to the treeprocessor """
        configs = self.getConfigs()
        self.patterns = OrderedDict()

        for k, v in REPL.items():
            if configs[k]:
                if isinstance(v[0], (list, tuple)):
                    for subv in v:
                        self.add_pattern(subv, md)
                else:
                    self.add_pattern(v, md)

        inlineProcessor = InlineProcessor(md)
        inlineProcessor.inlinePatterns = self.patterns
        md.treeprocessors.add('smart-symbols', inlineProcessor, '_end')
        if "smarty" in md.treeprocessors.keys():
            md.treeprocessors.link('smarty', '_end')

def makeExtension(*args, **kwargs):
    return SmartSymbolsExtension(*args, **kwargs)
<|endoftext|>


<commit_before>#!/usr/bin/env python

import re
from optparse import OptionParser

confPath = 'resources/cassandra/conf/'
hconfPath = 'resources/hadoop/conf/'
opsConfPath = '/etc/opscenter/'

clusterName = ''
seedList = ''
clusterSize = False
autoBootstrap = False
internalIP = ''
tokenPosition = -1

DEBUG = False

def promptUserInfo():
    global clusterName, seedList, clusterSize, autoBootstrap, internalIP, tokenPosition
    clusterName = raw_input("Cluster name:\n")

    seedList = raw_input("Seed list (comma-delimited):\n")
    seedList = seedList.replace(' ', '')
    seedList = seedList.split(',')
    seedList.sort()

    while (not type(clusterSize) is int):
        clusterSize = raw_input("Current cluster size:\n")
        try:
            clusterSize = int(clusterSize)
        except:
            print "Please enter a valid number."

    while not (autoBootstrap == 'y' or autoBootstrap == 'n'):
        autoBootstrap = raw_input("Is this node being autoBootStrapped? [y/n]\n").strip()
    if autoBootstrap == 'y':
        autoBootstrap = 'true'
    else:
        autoBootstrap = 'false'

    internalIP = raw_input("This node's internal IP address:\n")

    while (tokenPosition < 0) or (tokenPosition >= clusterSize):
        tokenPosition = raw_input("This node's token position (position < cluster size):\n")
        try:
            tokenPosition = int(tokenPosition)
        except:
            print "Please enter a valid number."

def commandLineSwitches():
    global clusterName, seedList, clusterSize, autoBootstrap, internalIP, tokenPosition, confPath, hconfPath, opsConfPath
    parser = OptionParser()
    parser.add_option("-n", "--clusterName", action="store", type="string", dest="clusterName", help="Set the cluster name.")
    parser.add_option("-l", "--seedList", action="store", type="string", dest="seedList", help="Provide a comma-delimited list of seeds.")
    parser.add_option("-s", "--clusterSize", action="store", type="int", dest="clusterSize", help="Provide the size of the cluster for equal partitioning.")
    parser.add_option("-a", "--autoBootstrap", action="store_true", dest="autoBootstrap", help="Set autobootstrap to true. (Defaults to false.)")
    parser.add_option("-i", "--internalIP", action="store", type="string", dest="internalIP", help="Set this nodes internal ip address.")
    parser.add_option("-t", "--tokenPosition", action="store", type="string", dest="tokenPosition", help="Set this node's token position.")

    parser.add_option("-c", "--confPath", action="store", type="string", dest="confPath", help="Set cassandra/conf/ path.")
    parser.add_option("-p", "--hconfPath", action="store", type="string", dest="hconfPath", help="Set hadoop/conf/ path.")

    (options, args) = parser.parse_args()
    if options:
        if options.clusterName:
            clusterName = options.clusterName
        if options.seedList:
            seedList = options.seedList
            seedList = seedList.replace(' ', '')
            seedList = seedList.split(',')
            seedList.sort()
        if options.clusterSize:
            clusterSize = options.clusterSize
        if options.autoBootstrap:
            autoBootstrap = options.autoBootstrap
        if options.internalIP:
            internalIP = options.internalIP
        if options.tokenPosition:
            tokenPosition = options.tokenPosition
        if options.confPath:
            confPath = options.confPath
        if options.hconfPath:
            hconfPath = options.hconfPath
        return True
    else:
        return False

def configureCassandraYaml():
    with open(confPath + 'cassandra.yaml', 'r') as f:
        yaml = f.read()

    # Set auto_bootstrap to true if expanding
    if autoBootstrap:
        yaml = yaml.replace('auto_bootstrap: false', 'auto_bootstrap: true')
    else:
        yaml = yaml.replace('auto_bootstrap: true', 'auto_bootstrap: false')

    # Create the seed list
    seedsYaml = ''
    for ip in seedList:
        seedsYaml += '     - ' + ip + '\n'
    if DEBUG:
        print "[DEBUG] seedsYaml: " + seedsYaml

    # Set seeds
    p = re.compile('seeds:(\s*-.*)*\s*#')
    yaml = p.sub('seeds:\n' + seedsYaml + '\n\n#', yaml)

    # Set listen_address
    p = re.compile('listen_address:.*\s*#')
    yaml = p.sub('listen_address: ' + internalIP + '\n\n#', yaml)

    # Set rpc_address
    yaml = yaml.replace('rpc_address: localhost', 'rpc_address: 0.0.0.0')

    # Set cluster_name to reservationid
    p = re.compile('cluster_name:.*\s*#')
    yaml = yaml.replace("cluster_name: \'" + clusterName + "\'\n\n#", yaml)

    print clusterName
    print yaml

    # Construct token for an equally split ring
    if clusterSize and tokenPosition:
        token = tokenPosition * (2**127 / int(clusterSize))
        p = re.compile( 'initial_token:(\s)*#')
        yaml = p.sub( 'initial_token: ' + str(token) + "\n\n#", yaml)

    # Brisk: Set to use different datacenters
    # yaml = yaml.replace('endpoint_snitch: org.apache.cassandra.locator.SimpleSnitch', 'endpoint_snitch: org.apache.cassandra.locator.PropertyFileSnitch')

    with open(confPath + 'cassandra.yaml', 'w') as f:
        f.write(yaml)

    print '[INFO] cassandra.yaml configured.'

def configureMapredSiteXML():
    with open(hconfPath + 'mapred-site.xml', 'r') as f:
        mapredSite = f.read()

    if len(seedList) > 0:
        mapredSite = mapredSite.replace('<value>localhost:8012</value>', '<value>' + seedList[0] + ':8012</value>')

    with open(hconfPath + 'mapred-site.xml', 'w') as f:
        f.write(mapredSite)

    print '[INFO] mapred-site.xml configured.'

def configureOpsCenterConf():
    try:
        with open(opsConfPath + 'opscenterd.conf', 'r') as f:
            opsConf = f.read()

        if len(seedList) > 0:
            opsConf = opsConf.replace('interface = 127.0.0.1', 'interface = 0.0.0.0')
            opsConf = opsConf.replace('seed_hosts = localhost', 'seed_hosts = ' + seedList[0])

        with open(opsConfPath + 'opscenterd.conf', 'w') as f:
            f.write(opsConf)

        print '[INFO] opscenterd.conf configured.'
    except:
        print '[INFO] opscenterd.conf not configured.'

if not commandLineSwitches():
    promptUserInfo()

configureCassandraYaml()
configureMapredSiteXML()
configureOpsCenterConf()
<commit_msg>configtool.py<commit_after>#!/usr/bin/env python

import re
from optparse import OptionParser

confPath = 'resources/cassandra/conf/'
hconfPath = 'resources/hadoop/conf/'
opsConfPath = '/etc/opscenter/'

clusterName = ''
seedList = ''
clusterSize = False
autoBootstrap = False
internalIP = ''
tokenPosition = -1

DEBUG = False

def promptUserInfo():
    global clusterName, seedList, clusterSize, autoBootstrap, internalIP, tokenPosition
    clusterName = raw_input("Cluster name:\n")

    seedList = raw_input("Seed list (comma-delimited):\n")
    seedList = seedList.replace(' ', '')
    seedList = seedList.split(',')
    seedList.sort()

    while (not type(clusterSize) is int):
        clusterSize = raw_input("Current cluster size:\n")
        try:
            clusterSize = int(clusterSize)
        except:
            print "Please enter a valid number."

    while not (autoBootstrap == 'y' or autoBootstrap == 'n'):
        autoBootstrap = raw_input("Is this node being autoBootStrapped? [y/n]\n").strip()
    if autoBootstrap == 'y':
        autoBootstrap = 'true'
    else:
        autoBootstrap = 'false'

    internalIP = raw_input("This node's internal IP address:\n")

    while (tokenPosition < 0) or (tokenPosition >= clusterSize):
        tokenPosition = raw_input("This node's token position (position < cluster size):\n")
        try:
            tokenPosition = int(tokenPosition)
        except:
            print "Please enter a valid number."

def commandLineSwitches():
    global clusterName, seedList, clusterSize, autoBootstrap, internalIP, tokenPosition, confPath, hconfPath, opsConfPath
    parser = OptionParser()
    parser.add_option("-n", "--clusterName", action="store", type="string", dest="clusterName", help="Set the cluster name.")
    parser.add_option("-l", "--seedList", action="store", type="string", dest="seedList", help="Provide a comma-delimited list of seeds.")
    parser.add_option("-s", "--clusterSize", action="store", type="int", dest="clusterSize", help="Provide the size of the cluster for equal partitioning.")
    parser.add_option("-a", "--autoBootstrap", action="store_true", dest="autoBootstrap", help="Set autobootstrap to true. (Defaults to false.)")
    parser.add_option("-i", "--internalIP", action="store", type="string", dest="internalIP", help="Set this nodes internal ip address.")
    parser.add_option("-t", "--tokenPosition", action="store", type="string", dest="tokenPosition", help="Set this node's token position.")

    parser.add_option("-c", "--confPath", action="store", type="string", dest="confPath", help="Set cassandra/conf/ path.")
    parser.add_option("-p", "--hconfPath", action="store", type="string", dest="hconfPath", help="Set hadoop/conf/ path.")

    (options, args) = parser.parse_args()
    if options:
        if options.clusterName:
            clusterName = options.clusterName
        if options.seedList:
            seedList = options.seedList
            seedList = seedList.replace(' ', '')
            seedList = seedList.split(',')
            seedList.sort()
        if options.clusterSize:
            clusterSize = options.clusterSize
        if options.autoBootstrap:
            autoBootstrap = options.autoBootstrap
        if options.internalIP:
            internalIP = options.internalIP
        if options.tokenPosition:
            tokenPosition = options.tokenPosition
        if options.confPath:
            confPath = options.confPath
        if options.hconfPath:
            hconfPath = options.hconfPath
        return True
    else:
        return False

def configureCassandraYaml():
    with open(confPath + 'cassandra.yaml', 'r') as f:
        yaml = f.read()

    # Set auto_bootstrap to true if expanding
    if autoBootstrap:
        yaml = yaml.replace('auto_bootstrap: false', 'auto_bootstrap: true')
    else:
        yaml = yaml.replace('auto_bootstrap: true', 'auto_bootstrap: false')

    # Create the seed list
    seedsYaml = ''
    for ip in seedList:
        seedsYaml += '     - ' + ip + '\n'
    if DEBUG:
        print "[DEBUG] seedsYaml: " + seedsYaml

    # Set seeds
    p = re.compile('seeds:(\s*-.*)*\s*#')
    yaml = p.sub('seeds:\n' + seedsYaml + '\n\n#', yaml)

    # Set listen_address
    p = re.compile('listen_address:.*\s*#')
    yaml = p.sub('listen_address: ' + internalIP + '\n\n#', yaml)

    # Set rpc_address
    yaml = yaml.replace('rpc_address: localhost', 'rpc_address: 0.0.0.0')

    # Set cluster_name to reservationid
    p = re.compile('cluster_name:.*\s*#')
    yaml = yaml.replace("cluster_name: " + clusterName + "\n\n#", yaml)

    print clusterName
    print yaml

    # Construct token for an equally split ring
    if clusterSize and tokenPosition:
        token = tokenPosition * (2**127 / int(clusterSize))
        p = re.compile( 'initial_token:(\s)*#')
        yaml = p.sub( 'initial_token: ' + str(token) + "\n\n#", yaml)

    # Brisk: Set to use different datacenters
    # yaml = yaml.replace('endpoint_snitch: org.apache.cassandra.locator.SimpleSnitch', 'endpoint_snitch: org.apache.cassandra.locator.PropertyFileSnitch')

    with open(confPath + 'cassandra.yaml', 'w') as f:
        f.write(yaml)

    print '[INFO] cassandra.yaml configured.'

def configureMapredSiteXML():
    with open(hconfPath + 'mapred-site.xml', 'r') as f:
        mapredSite = f.read()

    if len(seedList) > 0:
        mapredSite = mapredSite.replace('<value>localhost:8012</value>', '<value>' + seedList[0] + ':8012</value>')

    with open(hconfPath + 'mapred-site.xml', 'w') as f:
        f.write(mapredSite)

    print '[INFO] mapred-site.xml configured.'

def configureOpsCenterConf():
    try:
        with open(opsConfPath + 'opscenterd.conf', 'r') as f:
            opsConf = f.read()

        if len(seedList) > 0:
            opsConf = opsConf.replace('interface = 127.0.0.1', 'interface = 0.0.0.0')
            opsConf = opsConf.replace('seed_hosts = localhost', 'seed_hosts = ' + seedList[0])

        with open(opsConfPath + 'opscenterd.conf', 'w') as f:
            f.write(opsConf)

        print '[INFO] opscenterd.conf configured.'
    except:
        print '[INFO] opscenterd.conf not configured.'

if not commandLineSwitches():
    promptUserInfo()

configureCassandraYaml()
configureMapredSiteXML()
configureOpsCenterConf()
<|endoftext|>


<commit_before>import numpy as np
def sigmoid(X,prime=None):
	"""an activation function which outputs the value between (0,1)"""
	if isinstance(X,np.ndarray):
		if prime:
			return sigmoid(X)*(np.ones(len(X))-sigmoid(X))

		else:
			return 1.0/(1.0+np.exp(-X))
	else:
		X=np.array(X)
		return sigmoid(X)
		#return 1.0/(1.0+np.exp(-X))
def tanh(X):
	"""an activation function which outputs the value between (-1,1)"""
	if isinstance(X,np.ndarray):
		return (2.0/(1.0+np.exp(-(2*X))))-1
	else:
		X=np.array(X)
		return tanh(X)
def softmax(X):
	"""an activation function which outputs the value between (0,1)"""
	_X=np.full(X.shape,np.inf)
	for i in range(len(X)):
		_X[i]=exp(X[i])/(np.sum(np.exp(X),axis=0))
	return _X

<commit_msg>Update util.py<commit_after>from math import exp
import numpy as np
def sigmoid(X,prime=None):
	"""an activation function which outputs the value between (0,1)"""
	if isinstance(X,np.ndarray):
		if prime:
			return X * (np.ones(len(X))-(X))

		else:
			return 1.0/(1.0+np.exp(-X))
	else:
		X=np.array(X)
		return sigmoid(X)
		#return 1.0/(1.0+np.exp(-X))
def tanh(X):
	"""an activation function which outputs the value between (-1,1)"""
	if isinstance(X,np.ndarray):
		return (2.0/(1.0+np.exp(-(2*X))))-1
	else:
		X=np.array(X)
		return tanh(X)
def softmax(X):
	"""an activation function which outputs the value between (0,1)"""
	_X=np.full(X.shape,np.inf)
	for i in range(len(X)):
		_X[i]=exp(X[i])/(np.sum(np.exp(X),axis=0))
	return _X

<|endoftext|>


<commit_before>import random

import spacy

from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType

from .gender_agreement import (
    adjective_male_to_female,
    change_participle,
    check_change_verb,
    function_m2f,
    m2f_adjectives_animate_only,
    m2f_nouns,
    path_to_word_exists,
    unambiguous_pronouns,
)

def spanish_gender_swap(text, swap_names, seed=0, nlp=None):
    """Swap the gender of all gender-bearing nouns to female."""
    random.seed(seed)
    doc = nlp(text)
    r = get_replacements(doc, m2f_nouns)
    new_toks = [
        r[ii] + tok.whitespace_ if ii in r else tok.text + tok.whitespace_
        for ii, tok in enumerate(doc)
    ]
    return ["".join(new_toks)]

def modifiable_non_noun(token):
    word = token.text.lower()
    return token.pos_ not in ["NOUN", "PROPN"] or word in unambiguous_pronouns

def get_replacements(doc, m2f_nouns, debug=False):
    """Replace all nouns and pronouns whose gender can be swapped, and then
    swap all other words (adjectives, determiners, prepositions, participles)
    associated with them.
    """

    replacements = {}

    # See if we can swap the gender of nouns and pronouns.
    for token in doc:
        if (
            token.pos_ in ["NOUN", "PROPN", "PRON"]
            and token.text.lower() in m2f_nouns
        ):
            new_noun = m2f_nouns[token.text.lower()]
            if token.text[0].isupper():
                new_noun = new_noun.capitalize()
            replacements[token.i] = new_noun

    modified_tokens = [doc[ii] for ii in replacements]

    for modified_token in modified_tokens:

        # See if we can swap the gender of any of the noun's children.
        children = [c for c in modified_token.children]
        for c in children:
            if (
                modifiable_non_noun(c)
                and c.i not in replacements
                and c.pos_ in ["DET", "PRON", "ADP", "ADJ"]
            ):
                replacements[c.i] = swap_gender_of_word(c.text, c.pos_)
                if debug:
                    print("-------------------")
                    print("child added:", c.text, c.pos_, c.dep_)
                    print(
                        "child of token:", modified_token, modified_token.dep_
                    )

        # See if we can swap the gender of the noun's head.
        head = modified_token.head
        if modifiable_non_noun(head) and head.i not in replacements:
            # If the head is a verb, check to see if it is a participle
            # whose gender should agree with the noun.
            if check_change_verb(head, doc, replacements):
                replacements[head.i] = change_participle(head.text)
            elif (
                head.pos_ == "ADJ" and modified_token.dep_ != "nmod"
            ) or head.pos_ in ["DET", "PRON", "ADP"]:
                #  NOTE: prevent nmod to avoid cases like "lo bueno de mi primo."
                replacements[head.i] = swap_gender_of_word(
                    head.text, head.pos_
                )
            else:
                pass
            if debug:
                print("-------------------")
                print("head added:", head.text, head.pos_, head.dep_)
                print("head of token:", modified_token, modified_token.dep_)

    replacements = fix_remaining(doc, replacements)
    return replacements

def fix_remaining(doc, replacements, debug=False):
    """
    This function is used to do another pass over the sentence in order to:

    (1.) change the gender of other words, e.g., those connected by conjunctions
    ("italiano y rubio") or determiners ("el otro").
    (2.) modify any other adjectives which weren't changed previously due
    to incorrect POS tags or dependency parse. This only affects adjectives
    that are used to refer only to animate nouns.
    """

    for token in doc:
        if (
            token.pos_ in ["DET", "PRON", "ADP", "ADJ"]
            and token.i not in replacements
            and path_to_word_exists(token, replacements)
        ):
            replacements[token.i] = swap_gender_of_word(token.text, token.pos_)
            if debug:
                print("-------------------")
                print("head2: ", token.head.text, token.head.pos_)
                print("token:", token, token.dep_)

    # This shouldn't be necessary, but sometimes the POS tagger fails, so now
    # swap more adjectives which we know modify animate nouns.
    for token in doc:
        if (
            token.pos_ == "ADJ"
            and token.text.lower() in m2f_adjectives_animate_only
        ):
            uppercase = token.text[0].isupper()
            n = m2f_adjectives_animate_only[token.text.lower()]
            replacements[token.i] = n.capitalize() if uppercase else n

    return replacements

def swap_gender_of_word(word, pos):
    """The nouns are based on a gazetter.  But this function is used to
    change the gender of adjectives, determiners, etc.
    """

    uppercase = word[0].isupper()

    # Avoid mistakes caused by incorrect POS tags by treating
    # DET, PRON, ADP all at once.
    if pos in ["DET", "PRON", "ADP"] or word in unambiguous_pronouns:
        n = (
            function_m2f[word.lower()]
            if word.lower() in function_m2f
            else word.lower()
        )
    elif pos == "ADJ":
        n = adjective_male_to_female(word.lower())
    else:
        raise ValueError("This is a verb.")

    if uppercase:
        n = n.capitalize()

    return n

class SpanishGenderSwap(SentenceOperation):
    """Swaps all gendered nouns (and any other associated words, in order to
    maintain grammatical agreement) to their female counterparts.

    Args:
        swap_names: Also swap person names? Defaults: False.
        seed: initial seed. Defaults: 0.
    """

    tasks = [
        TaskType.TEXT_CLASSIFICATION,
        TaskType.TEXT_TO_TEXT_GENERATION,
        TaskType.TEXT_TAGGING,
    ]
    languages = ["es"]

    def __init__(self, swap_names=False, seed=0):
        super().__init__(seed)
        self.swap_names = swap_names
        self.nlp = spacy.load("es_core_news_lg")

    def generate(self, sentence: str):
        perturbed_texts = spanish_gender_swap(
            text=sentence,
            swap_names=self.swap_names,
            seed=self.seed,
            nlp=self.nlp,
        )
        return perturbed_texts
<commit_msg>I will implement gender name swaps soon.<commit_after>import random

import spacy

from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType

from .gender_agreement import (
    adjective_male_to_female,
    change_participle,
    check_change_verb,
    function_m2f,
    m2f_adjectives_animate_only,
    m2f_nouns,
    path_to_word_exists,
    unambiguous_pronouns,
)

def spanish_gender_swap(text, swap_names, seed=0, nlp=None):
    """Swap the gender of all gender-bearing nouns to female."""
    if swap_names:
        raise NotImplementedError("Will implemented here shortly.")
    random.seed(seed)
    doc = nlp(text)
    r = get_replacements(doc, m2f_nouns)
    new_toks = [
        r[ii] + tok.whitespace_ if ii in r else tok.text + tok.whitespace_
        for ii, tok in enumerate(doc)
    ]
    return ["".join(new_toks)]

def modifiable_non_noun(token):
    word = token.text.lower()
    return token.pos_ not in ["NOUN", "PROPN"] or word in unambiguous_pronouns

def get_replacements(doc, m2f_nouns, debug=False):
    """Replace all nouns and pronouns whose gender can be swapped, and then
    swap all other words (adjectives, determiners, prepositions, participles)
    associated with them.
    """

    replacements = {}

    # See if we can swap the gender of nouns and pronouns.
    for token in doc:
        if (
            token.pos_ in ["NOUN", "PROPN", "PRON"]
            and token.text.lower() in m2f_nouns
        ):
            new_noun = m2f_nouns[token.text.lower()]
            if token.text[0].isupper():
                new_noun = new_noun.capitalize()
            replacements[token.i] = new_noun

    modified_tokens = [doc[ii] for ii in replacements]

    for modified_token in modified_tokens:

        # See if we can swap the gender of any of the noun's children.
        children = [c for c in modified_token.children]
        for c in children:
            if (
                modifiable_non_noun(c)
                and c.i not in replacements
                and c.pos_ in ["DET", "PRON", "ADP", "ADJ"]
            ):
                replacements[c.i] = swap_gender_of_word(c.text, c.pos_)
                if debug:
                    print("-------------------")
                    print("child added:", c.text, c.pos_, c.dep_)
                    print(
                        "child of token:", modified_token, modified_token.dep_
                    )

        # See if we can swap the gender of the noun's head.
        head = modified_token.head
        if modifiable_non_noun(head) and head.i not in replacements:
            # If the head is a verb, check to see if it is a participle
            # whose gender should agree with the noun.
            if check_change_verb(head, doc, replacements):
                replacements[head.i] = change_participle(head.text)
            elif (
                head.pos_ == "ADJ" and modified_token.dep_ != "nmod"
            ) or head.pos_ in ["DET", "PRON", "ADP"]:
                #  NOTE: prevent nmod to avoid cases like "lo bueno de mi primo."
                replacements[head.i] = swap_gender_of_word(
                    head.text, head.pos_
                )
            else:
                pass
            if debug:
                print("-------------------")
                print("head added:", head.text, head.pos_, head.dep_)
                print("head of token:", modified_token, modified_token.dep_)

    replacements = fix_remaining(doc, replacements)
    return replacements

def fix_remaining(doc, replacements, debug=False):
    """
    This function is used to do another pass over the sentence in order to:

    (1.) change the gender of other words, e.g., those connected by conjunctions
    ("italiano y rubio") or determiners ("el otro").
    (2.) modify any other adjectives which weren't changed previously due
    to incorrect POS tags or dependency parse. This only affects adjectives
    that are used to refer only to animate nouns.
    """

    for token in doc:
        if (
            token.pos_ in ["DET", "PRON", "ADP", "ADJ"]
            and token.i not in replacements
            and path_to_word_exists(token, replacements)
        ):
            replacements[token.i] = swap_gender_of_word(token.text, token.pos_)
            if debug:
                print("-------------------")
                print("head2: ", token.head.text, token.head.pos_)
                print("token:", token, token.dep_)

    # This shouldn't be necessary, but sometimes the POS tagger fails, so now
    # swap more adjectives which we know modify animate nouns.
    for token in doc:
        if (
            token.pos_ == "ADJ"
            and token.text.lower() in m2f_adjectives_animate_only
        ):
            uppercase = token.text[0].isupper()
            n = m2f_adjectives_animate_only[token.text.lower()]
            replacements[token.i] = n.capitalize() if uppercase else n

    return replacements

def swap_gender_of_word(word, pos):
    """The nouns are based on a gazetter.  But this function is used to
    change the gender of adjectives, determiners, etc.
    """

    uppercase = word[0].isupper()

    # Avoid mistakes caused by incorrect POS tags by treating
    # DET, PRON, ADP all at once.
    if pos in ["DET", "PRON", "ADP"] or word in unambiguous_pronouns:
        n = (
            function_m2f[word.lower()]
            if word.lower() in function_m2f
            else word.lower()
        )
    elif pos == "ADJ":
        n = adjective_male_to_female(word.lower())
    else:
        raise ValueError("This is a verb.")

    if uppercase:
        n = n.capitalize()

    return n

class SpanishGenderSwap(SentenceOperation):
    """Swaps all gendered nouns (and any other associated words, in order to
    maintain grammatical agreement) to their female counterparts.

    Args:
        swap_names: Also swap person names? Defaults: False.
        seed: initial seed. Defaults: 0.
    """

    tasks = [
        TaskType.TEXT_CLASSIFICATION,
        TaskType.TEXT_TO_TEXT_GENERATION,
        TaskType.TEXT_TAGGING,
    ]
    languages = ["es"]

    def __init__(self, swap_names=False, seed=0):
        super().__init__(seed)
        self.swap_names = swap_names
        self.nlp = spacy.load("es_core_news_lg")

    def generate(self, sentence: str):
        perturbed_texts = spanish_gender_swap(
            text=sentence,
            swap_names=self.swap_names,
            seed=self.seed,
            nlp=self.nlp,
        )
        return perturbed_texts
<|endoftext|>


<commit_before>#!/usr/bin/env python
import glob
import mmap
import sys
import traceback

from mmstats import defaults, reader as mmstats_reader

def err(*args):
    """Laziness"""
    sys.stderr.write('%s\n' % ' '.join(map(str, args)))

def slurp_stats(full_fn, m):
    """mmap parsing mainloop"""
    reader = mmstats_reader.MmStatsReader(m)

    print '==>', full_fn
    out = []
    label_max = 0
    for label, value in reader:
        if len(label) > label_max:
            label_max = len(label)
        out.append((label, value))

    for label, value in out:
        if isinstance(value, str):
            value = value.split('\x00', 1)[0]
        print ('  %-' + str(label_max) + 's %s') % (label, value)
    print

def main():
    """MmStats CLI Entry point"""
    # Accept paths and dirs to read as mmstats files from the command line
    stats_files = set()
    for arg in sys.argv[1:]:
        stats_files.add(arg)

    # Only read from tempdir if no files specified on the command line
    if not stats_files:
        stats_files = glob.glob(defaults.DEFAULT_GLOB)

    for fn in stats_files:
        with open(fn) as f:
            try:
                mmst = mmap.mmap(f.fileno(), 0, prot=mmap.ACCESS_READ)
                slurp_stats(fn, mmst)
            except Exception:
                err('Error reading: %s' % fn)
                err(traceback.format_exc())
            finally:
                mmst.close()

if __name__ == '__main__':
    main()
<commit_msg>Handle broken pipes in slurpstats<commit_after>#!/usr/bin/env python
import errno
import glob
import mmap
import sys
import traceback

from mmstats import defaults, reader as mmstats_reader

def err(*args):
    """Laziness"""
    sys.stderr.write('%s\n' % ' '.join(map(str, args)))

def slurp_stats(full_fn, m):
    """mmap parsing mainloop"""
    reader = mmstats_reader.MmStatsReader(m)

    print '==>', full_fn
    out = []
    label_max = 0
    for label, value in reader:
        if len(label) > label_max:
            label_max = len(label)
        out.append((label, value))

    for label, value in out:
        if isinstance(value, str):
            value = value.split('\x00', 1)[0]
        print ('  %-' + str(label_max) + 's %s') % (label, value)
    print

def main():
    """MmStats CLI Entry point"""
    # Accept paths and dirs to read as mmstats files from the command line
    stats_files = set()
    for arg in sys.argv[1:]:
        stats_files.add(arg)

    # Only read from tempdir if no files specified on the command line
    if not stats_files:
        stats_files = glob.glob(defaults.DEFAULT_GLOB)

    for fn in stats_files:
        with open(fn) as f:
            mmst = None
            try:
                mmst = mmap.mmap(f.fileno(), 0, prot=mmap.ACCESS_READ)
                slurp_stats(fn, mmst)
            except IOError as ex:
                if ex.errno == errno.EPIPE:
                    # A broken pipe (probably) means the process was killed
                    # while piped to another command (e.g.: grep) - so die
                    return
                else:
                    err('Error reading: %s' % fn)
                    err(traceback.format_exc())
            except Exception:
                err('Error reading: %s' % fn)
                err(traceback.format_exc())
            finally:
                if mmst is not None:
                    mmst.close()

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-
##############################################################################
#
#    Author: Mag Guevara. Copyright ClearCorp SA
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import osv, fields

class report_webkit_format(osv.osv):
	_name = "ir.header_webkit"
	_inherit = "ir.header_webkit"
	_columns = {
		'format': fields.selection( [
				('A0' ,'A0  5   841 x 1189 mm'),
				('A1' ,'A1  6   594 x 841 mm'),
				('A2' ,'A2  7   420 x 594 mm'),
				('A3' ,'A3  8   297 x 420 mm'),
				('A4' ,'A4  0   210 x 297 mm, 8.26 x 11.69 inches'),
				('A5' ,'A5  9   148 x 210 mm'),
				('A6' ,'A6  10  105 x 148 mm'),
				('A7' ,'A7  11  74 x 105 mm'),
				('A8' ,'A8  12  52 x 74 mm'),
				('A9' ,'A9  13  37 x 52 mm'),
				('B0' ,'B0  14  1000 x 1414 mm'),
				('B1' ,'B1  15  707 x 1000 mm'),
				('B2' ,'B2  17  500 x 707 mm'),
				('B3' ,'B3  18  353 x 500 mm'),
				('B4' ,'B4  19  250 x 353 mm'),
				('B5' ,'B5  1   176 x 250 mm, 6.93 x 9.84 inches'),
				('B6' ,'B6  20  125 x 176 mm'),
				('B7' ,'B7  21  88 x 125 mm'),
				('B8' ,'B8  22  62 x 88 mm'),
				('B9' ,'B9  23  33 x 62 mm'),
				('B10',':B10    16  31 x 44 mm'),
				('C5E','C5E 24  163 x 229 mm'),
				('Checks','Checks 25  171 x 180 mm'),
				('Comm10E','Comm10E 26  105 x 241 mm, U.S. Common 10 Envelope'),
				('DLE', 'DLE 27 110 x 220 mm'),
				('Executive','Executive 4   7.5 x 10 inches, 190.5 x 254 mm'),
				('Folio','Folio 28  210 x 330 mm'),
				('Ledger', 'Ledger  29  431.8 x 279.4 mm'),
				('Legal', 'Legal    3   8.5 x 14 inches, 215.9 x 355.6 mm'),
				('Letter','Letter 2 8.5 x 11 inches, 215.9 x 279.4 mm'),
				('Tabloid', 'Tabloid 29 279.4 x 431.8 mm'),
				],
				'Paper size',
				required=True,
				help="Select Proper Paper size"
			)
	}
report_webkit_format()
<commit_msg>[FIX] report_webkit format<commit_after># -*- encoding: utf-8 -*-
##############################################################################
#
#    Author: Mag Guevara. Copyright ClearCorp SA
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import osv, fields

class report_webkit_format(osv.osv):
	_name = "ir.header_webkit"
	_inherit = "ir.header_webkit"
	_columns = {
		'format': fields.selection( [
				('A0' ,'A0  5   841 x 1189 mm'),
				('A1' ,'A1  6   594 x 841 mm'),
				('A2' ,'A2  7   420 x 594 mm'),
				('A3' ,'A3  8   297 x 420 mm'),
				('A4' ,'A4  0   210 x 297 mm, 8.26 x 11.69 inches'),
				('A5' ,'A5  9   148 x 210 mm'),
				('A6' ,'A6  10  105 x 148 mm'),
				('A7' ,'A7  11  74 x 105 mm'),
				('A8' ,'A8  12  52 x 74 mm'),
				('A9' ,'A9  13  37 x 52 mm'),
				('B0' ,'B0  14  1000 x 1414 mm'),
				('B1' ,'B1  15  707 x 1000 mm'),
				('B2' ,'B2  17  500 x 707 mm'),
				('B3' ,'B3  18  353 x 500 mm'),
				('B4' ,'B4  19  250 x 353 mm'),
				('B5' ,'B5  1   176 x 250 mm, 6.93 x 9.84 inches'),
				('B6' ,'B6  20  125 x 176 mm'),
				('B7' ,'B7  21  88 x 125 mm'),
				('B8' ,'B8  22  62 x 88 mm'),
				('B9' ,'B9  23  33 x 62 mm'),
				('B10',':B10    16  31 x 44 mm'),
				('C5E','C5E 24  163 x 229 mm'),
				('C5E','C5E 25  171 x 180 mm'),
				('Comm10E','Comm10E 26  105 x 241 mm, U.S. Common 10 Envelope'),
				('DLE', 'DLE 27 110 x 220 mm'),
				('Executive','Executive 4   7.5 x 10 inches, 190.5 x 254 mm'),
				('Folio','Folio 28  210 x 330 mm'),
				('Ledger', 'Ledger  29  431.8 x 279.4 mm'),
				('Legal', 'Legal    3   8.5 x 14 inches, 215.9 x 355.6 mm'),
				('Letter','Letter 2 8.5 x 11 inches, 215.9 x 279.4 mm'),
				('Tabloid', 'Tabloid 29 279.4 x 431.8 mm'),
				],
				'Paper size',
				required=True,
				help="Select Proper Paper size"
			)
	}
report_webkit_format()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from openerp import _, api, fields, models

class ProductTemplate(models.Model):
    _inherit = 'product.template'

    is_line = fields.Boolean(
        string=_('Line Product'),
        default=False,
    )

    family_id = fields.Many2one(
        'product.family',
        string=_('Family'),
    )

    group_id = fields.Many2one(
        'product.group',
        string=_('Group'),
    )

    line_id = fields.Many2one(
        'product.line',
        string=_('Line'),
    )

    type_id = fields.Many2one(
        'product.type',
        string=_('Type'),
    )
    cutting_detail = fields.Boolean(
        string='Requires cutting detail',
    )

    @api.model
    def _get_buy_route(self):
        make_route = self.env.ref('stock.route_warehouse0_mto')
        if make_route:
            return make_route.ids
        return []
<commit_msg>no copy some fields<commit_after># -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from openerp import _, api, fields, models

class ProductTemplate(models.Model):
    _inherit = 'product.template'

    is_line = fields.Boolean(
        string=_('Line Product'),
        copy=False,
        default=False,
    )

    family_id = fields.Many2one(
        'product.family',
        string=_('Family'),
    )

    group_id = fields.Many2one(
        'product.group',
        string=_('Group'),
    )

    line_id = fields.Many2one(
        'product.line',
        copy=False,
        string=_('Line'),
    )

    type_id = fields.Many2one(
        'product.type',
        string=_('Type'),
    )
    cutting_detail = fields.Boolean(
        string='Requires cutting detail',
    )

    @api.model
    def _get_buy_route(self):
        make_route = self.env.ref('stock.route_warehouse0_mto')
        if make_route:
            return make_route.ids
        return []
<|endoftext|>