text:
"""

Item handling module for lpm

An item consists of
- a serial number
- a part number
- a project association (optional)
- a status
- a 'available' flag (true/false)
- a list of comments

For each part number, a custom view may be defined through the LPM_ITEM_VIEW_MAP config entry.
Additional required fields for a part number may be defined through the LPM_ITEM_IMPORT_MAP config entry.

The status can contain an arbitrary string. However, the list of valid status entries can be defined in the
LPM_ITEM_STATUS_MAP config entry, where a graph of valid status transitions can be defined. In addition,
the map defines which value the 'available' flag shall have and which role is required to do the transition.

The rules of access are as follows:
- anyone may view items and add comments
- item_admin users may additionally import new items
- status changes may require a special role, depending on the LPM_ITEM_STATUS_MAP entry.

:copyright: (c) 2016 Hannes Friederich.
:license: BSD, see LICENSE for more details.
"""

from datetime import datetime
from collections import defaultdict
from flask import Blueprint, request, current_app, flash, url_for, redirect, render_template
from flask.ext.login import login_required, current_user
from flask_wtf import Form
from wtforms import TextAreaField, StringField, SubmitField
from wtforms.validators import InputRequired
from lpm.login import role_required
from lpm.utils import extract_errors
from lpm.components import ensure_exists, PartNumber
from lpm.stock import update_batch, update_counts
from lpm.xls_files import FileForm, read_xls, save_to_tmp, extract_filepath

bp = Blueprint('items', __name__)

class CommentForm(Form):
    message = TextAreaField(label='Message', validators=[InputRequired()])

class StatusForm(Form):
    status = StringField(label='New Status', validators=[InputRequired()])
    project = StringField(label='Project')
    comment = TextAreaField(label='Comment')

class ProjectForm(Form):
    project = StringField(label='Project', validators=[InputRequired()])

@bp.route('/')
@login_required
def overview():
    """
    Shows the overview page with all items of the database
    """
    filter = {'available': True}
    if request.args.get('show_all'):
        filter = None
    objects = list(current_app.mongo.db.items.find(
            filter=filter,
            projection=['partno', 'project', 'status']
    ))
    component_records = current_app.mongo.db.components.find(projection=['name'])
    names = dict((record['_id'], record['name']) for record in component_records)
    for obj in objects:
        partno = PartNumber(obj['partno'])
        obj['_partname'] = names.get(partno.base_number, '<unknown>')
    return render_template('items/overview.html', data=objects, show_all=request.args.get('show_all'))

@bp.route('/<serial>/')
@login_required
def details(serial):
    obj = current_app.mongo.db.items.find_one_or_404(serial)
    try:
        pn = PartNumber(obj.get('partno'))
    except ValueError:
        flash('An error occurred while parsing the part number', 'error')
        return redirect(url_for('items.overview'))

    component = current_app.mongo.db.components.find_one(pn.base_number)
    if component:
        obj['_partname'] = component['name']
    else:
        obj['_partname'] = 'n/a'

    # First try the full part number, then only the base number. Use default.html as fallback
    mapping = current_app.config.get('LPM_ITEM_VIEW_MAP', dict())
    filename = mapping.get(pn.id) or mapping.get(pn.base_number) or 'default.html'
    try:
        return render_template('items/' + filename, item=obj, error=None)
    except Exception as e:
        return render_template('items/details.html', item=obj, error=str(e))

@bp.route('/<serial>/add-comment', methods=['GET', 'POST'])
@login_required
def add_comment(serial):
    current_app.mongo.db.items.find_one_or_404(serial)
    form = CommentForm(request.form)
    if request.method == 'POST' and form.validate_on_submit():
        result = current_app.mongo.db.items.update_one(
                filter={'_id': serial},
                update={'$push': {'comments': create_comment(form.message.data)}}
        )
        if result.modified_count == 1:
            flash('comment successfully added', 'success')
        else:
            flash('comment adding failed, please contact the administrator', 'error')
        return redirect(url_for('items.details', serial=serial))
    extract_errors(form)
    return render_template('items/comment_form.html', form=form, serial=serial)

@bp.route('/<serial>/change-status/<status>', methods=['GET', 'POST'])
@bp.route('/<serial>/change-status', methods=['GET', 'POST'])
@login_required
def change_status(serial, status=''):
    """
    Changes the status of the given item to the specified value
    """
    form = StatusForm(request.form)
    item = current_app.mongo.db.items.find_one_or_404(serial, projection=['partno', 'status'])

    if request.method == 'POST' and form.validate_on_submit():
        try:
            do_update_status(item, form.status.data, form.project.data, form.comment.data)
            flash('status successfully updated', 'success')
            return redirect(url_for('items.details', serial=serial))

        except Exception as e:
            flash(e, 'error')

    extract_errors(form)
    if status is not None:
        form.status.data=status
    return render_template('items/status_form.html', serial=serial, item=item, form=form)

@bp.route('/<serial>/set-project', methods=['GET', 'POST'])
@login_required
def set_project(serial):
    """
    Changes the project association of the given item to the specified value
    """
    form = ProjectForm(request.form)
    current_app.mongo.db.items.find_one_or_404(serial)

    if request.method == 'POST' and form.validate_on_submit():
        project = form.project.data
        comment = create_comment("[Auto] changed project association to '%s'" % project)
        result = current_app.mongo.db.items.update_one(
                filter={'_id': serial},
                update={
                    '$set': {'project': project},
                    '$push': {'comments': comment}
                }
        )
        if result.modified_count == 1:
            flash('project successfully set', 'success')
        else:
            flash('failed to set the project, please contact the administrator', 'error')
        return redirect(url_for('items.details', serial=serial))
    extract_errors(form)
    return render_template('items/project_form.html', form=form, serial=serial)

@bp.route('/import', methods=['GET', 'POST'])
@role_required('item_admin')
def import_items():
    form = FileForm(request.form)
    # WTF is NOT used for the file handling, since the file upload handling seems broken.
    if request.method == 'POST' and form.validate_on_submit():
        # show the validation page if a file is uploaded
        # else process the tmpname parameter
        if request.files.get('file'):  # a file was uploaded
            try:
                save_to_tmp(form)
                success, headers, values = _import_file(extract_filepath(form))
                return render_template('items/validate_form.html',
                                       title='Verify Item Data',
                                       form=form,
                                       headers=headers,
                                       data=values)
            except Exception as e:
                flash(e, 'error')

        elif form.tmpname.data:
            # re-run the data import and insert items into the database
            success, headers, values = _import_file(extract_filepath(form))
            if success:
                try:
                    _store_items(values)
                    flash('item import successful', 'success')
                    return redirect(url_for('items.overview'))
                except Exception as e:
                    flash(e, 'error')
            return render_template('items/validate_form.html',
                                   title='Verify Item Data',
                                   form=form,
                                   headers=headers,
                                   data=values)

    extract_errors(form)
    return render_template('items/import_form.html', title='Import Items File', form=form)

def get_requirements(partno):
    reqs = current_app.config['LPM_ITEM_IMPORT_MAP']
    return reqs.get(partno.id) or reqs.get(partno.base_number) or dict()

def process_requirements(obj, reqs):
    required_fields = reqs.get('required_fields', list())
    date_fields = reqs.get('date_fields', list())
    integer_fields = reqs.get('integer_fields', list())
    floating_point_fields = reqs.get('floating_point_fields', list())
    boolean_fields = reqs.get('boolean_fields', list())

    for key in required_fields:
        if key not in obj:
            raise ValueError("required field '%s' is missing" % key)

    for key, value in obj.items():
        if key in date_fields:
            if not isinstance(value, datetime):
                raise ValueError("field '%s' must be a datetime object" % key)
        elif key in integer_fields:
            obj[key] = int(value)
        elif key in floating_point_fields:
            obj[key] = float(value)
        elif key in boolean_fields:
            value = str(value)
            if value == '0' or value.lower() == 'false' or value.lower() == 'no':
                obj[key] = False
            elif value == '1' or value.lower() == 'true' or value.lower() == 'yes':
                obj[key] = True
            else:
                raise ValueError("cannot parse field '%s' as a boolean" % key)
        else:
            obj[key] = str(obj[key])

    # need to check the status transition validity
    if 'status' in obj:
        _check_status(obj.get('partno'), '', obj.get('status'))

def create_comment(comment, date=None):
    """
    Creates a comment object
    """
    if date is None:
        date = datetime.now()
    return {'user': current_user.id, 'date': date, 'message': comment}

def do_update_status(item, status, project=None, comment=None, now=datetime.now()):
    setdata = {}
    comments = []
    _check_status(item.get('partno'), item.get('status'), status)
    setdata['status'] = status
    setdata['available'] = not _is_unavailable(item.get('partno'), status)
    if project:
        setdata['project'] = project
    comments.append(create_comment("[Auto] changed status to '%s'" % status, now))
    if comment:
        comments.append(create_comment(comment, now))

    result = current_app.mongo.db.items.update_one(
        filter={'_id': item.get('_id')},
        update={
            '$set': setdata,
            '$push': {'comments': {'$each': comments}}
        }
    )
    if result.modified_count != 1:
        raise RuntimeError('status update failed, please contact the administrator')

def _import_file(filepath):
    """
    Processes the XLS data, ensures that the part numbers exist (incl. revision)
    and that all the required fields are set.
    If something is missing a warning is flashed but processing continues.
    Returns a tuple (success, headers, data)
    """
    headers, data = read_xls(filepath)
    success = True
    if 'partno' not in headers:
        raise ValueError("'partno' column is missing")
    if 'serial' not in headers:
        raise ValueError("'serial' column is missing")
    if '_id' in headers:
        raise ValueError("reserved column name: '_id'")
    if 'comments' in headers:
        raise ValueError("reserved column name: 'comments'")
    if 'available' in headers:
        raise ValueError("reserved column name: 'available'")
    for idx, item in enumerate(data):
        try:
            pn = PartNumber(item.get('partno'))
            ensure_exists(pn.base_number)
            if pn.revision is None:
                raise ValueError('part number requires a revision')
            serial = item.get('serial')
            if not serial:
                raise ValueError('serial number is missing')
            # transform the serial to a string AFTER checking it exists. Otherwise the string would read 'None'
            serial = str(serial)
            if current_app.mongo.db.items.find_one(serial):
                raise ValueError("serial number '%s' exists already" % serial)

            reqs = get_requirements(pn)
            process_requirements(item, reqs)
        except Exception as e:
            flash('%s (row %d)' % (e, (idx+2)), 'error')
            success = False
    return success, headers, data

def _store_items(data):
    """
    Saves the provided items in the database.
    Applied transformations:
    The 'serial' key is transformed to the '_id' key
    A 'comment' key is pushed to the comments array
    """
    quantities = defaultdict(int)  # for the stock update
    now = datetime.now()
    for idx, item in enumerate(data):
        assert 'serial' in item
        assert 'partno' in item
        item['_id'] = item.pop('serial')
        if 'project' not in item:
            item['project'] = ''
        if 'status' in item:
            item['available'] = not _is_unavailable(item['partno'], item['status'])
        else:
            item['status'] = ''
            item['available'] = True
        comments = [create_comment('[Auto] created', now)]
        comment = item.pop('comment', None)
        if comment:
            comments.append(create_comment(comment, now))
        item['comments'] = comments
        current_app.mongo.db.items.insert(item)

        # count the number of occurrences per model number
        partno = PartNumber(item.get('partno'))
        quantities[partno.base_number] += 1

        # update the batch information if present
        batch = item.get('batch')
        if batch:
            update_batch(partno.base_number, batch, 1)

    # add the items to the stock as well
    for partno, value in quantities.items():
        update_counts(partno, value, None, 'items added')

def _check_status(partno, current_status, new_status):
    pn = PartNumber(partno)
    partmap = current_app.config.get('LPM_ITEM_STATUS_MAP', dict())
    map = partmap.get(pn.id) or partmap.get(pn.base_number) or partmap.get('default') or dict()
    if new_status not in map:
        raise ValueError("unknown status: '%s'" % new_status)
    definition = map.get(new_status)
    origins = definition.get('origins')
    if current_status not in origins:
        raise ValueError("Invalid status transition: from '%s' to '%s'" % (current_status, new_status))
    role = definition.get('role')
    if role and not current_user.has_role(role):
        raise ValueError("insufficient permissions to do the status transition from '%s' to '%s'"
                         % (current_status, new_status))

def _is_unavailable(partno, status):
    pn = PartNumber(partno)
    partmap = current_app.config.get('LPM_ITEM_STATUS_MAP', dict())
    map = partmap.get(pn.id) or partmap.get(pn.base_number) or partmap.get('default') or dict()
    definition = map.get(status)
    return definition.get('unavailable', False)


text: The JPA Maven Plugin makes unit testing your Maven-based JPA projects easier.

redpajama_set_name: RedPajamaGithub


text:
import Vue from 'vue'
import $ from 'jquery'
import TypeaheadDoc from '@docs/pages/components/Typeahead.md'
import utils from '../utils'

describe('Typeahead', () => {
  let xhr, requests, server
  let vm
  let $el

  beforeEach(() => {
    const Constructor = Vue.extend(TypeaheadDoc)
    vm = new Constructor().$mount()
    $el = $(vm.$el).appendTo('body')
  })

  afterEach(() => {
    vm.$destroy()
    $el.remove()
  })

  before(() => {
    xhr = sinon.useFakeXMLHttpRequest()
    requests = []
    xhr.onCreate = (req) => {
      requests.push(req)
    }
    server = sinon.fakeServer.create()
  })

  after(() => {
    xhr.restore()
    server.restore()
  })

  it('should be able to set and clear typeahead model manually', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const setBtn = _vm.$el.querySelectorAll('.btn')[0]
    const clearBtn = _vm.$el.querySelectorAll('.btn')[1]
    const input = _vm.$el.querySelector('input')
    setBtn.click()
    await vm.$nextTick()
    expect(input.value).to.equal('Alabama')
    expect(_vm.model.name).to.equal('Alabama')
    expect(_vm.model.abbreviation).to.equal('AL')
    clearBtn.click()
    await vm.$nextTick()
    expect(input.value).to.equal('')
    expect(_vm.model).not.exist
  })

  it('should be able to open typeahead when input change', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(3)
    const selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alabama')
  })

  it('should be able to open typeahead on input focus', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'focus')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(3)
    const selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alabama')
  })

  it('should be able to keep open on input click', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'focus')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    input.click()
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
  })

  it('should be able to close typeahead on input blur', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    utils.triggerEvent(input, 'blur')
    await vm.$nextTick()
    expect(dropdown.className).not.contain('open')
  })

  it('should be able to close typeahead on input esc key', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    utils.triggerKey(input, utils.keyCodes.esc)
    await vm.$nextTick()
    expect(dropdown.className).not.contain('open')
  })

  it('should not close typeahead on input click', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    utils.triggerEvent(input, 'click')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
  })

  it('should be able to close typeahead when input changed to empty', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    input.value = ''
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.not.contain('open')
  })

  it('should be able to slice item length', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'a'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(10)
    const selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alabama')
  })

  it('should not open dropdown if nothing match', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'asdasdasdasd'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.not.contain('open')
  })

  it('should be able to select item', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(3)
    const selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alabama')
    selected.click()
    await vm.$nextTick()
    expect(dropdown.className).to.not.contain('open')
    expect(input.value).to.equal('Alabama')
    expect(_vm.model.name).to.equal('Alabama')
  })

  it('should be able to use force select', async () => {
    const _vm = vm.$refs['typeahead-force-select']
    _vm.forceSelect = true
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(_vm.model).not.exist
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(3)
    const selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alabama')
    selected.click()
    await vm.$nextTick()
    expect(dropdown.className).to.not.contain('open')
    expect(input.value).to.equal('Alabama')
    expect(_vm.model.name).to.equal('Alabama')
  })

  it('should not be able to select item using keyboard while dropdown not open', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    utils.triggerKey(input, utils.keyCodes.enter, 'down')
    await vm.$nextTick()
    expect(dropdown.className).to.not.contain('open')
    expect(input.value).to.equal('')
  })

  it('should be able to select item using keyboard', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(3)
    const selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alabama')
    utils.triggerKey(input, 13)
    await vm.$nextTick()
    expect(dropdown.className).to.not.contain('open')
    expect(input.value).to.equal('Alabama')
    expect(_vm.model.name).to.equal('Alabama')
  })

  it('should be able use keyboard nav to go next', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(3)
    let selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alabama')
    utils.triggerKey(input, 40)
    await vm.$nextTick()
    selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alaska')
    utils.triggerKey(input, 40)
    await vm.$nextTick()
    utils.triggerKey(input, 40)
    await vm.$nextTick()
    selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Palau')
  })

  it('should be able use keyboard nav to go prev', async () => {
    const _vm = vm.$refs['typeahead-example']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(3)
    let selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alabama')
    utils.triggerKey(input, 40)
    await vm.$nextTick()
    utils.triggerKey(input, 40)
    await vm.$nextTick()
    utils.triggerKey(input, 40)
    await vm.$nextTick()
    selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Palau')
    utils.triggerKey(input, 38)
    await vm.$nextTick()
    selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alaska')
    utils.triggerKey(input, 38)
    await vm.$nextTick()
    utils.triggerKey(input, 38)
    await vm.$nextTick()
    selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('Alabama')
  })

  it('should be able to match start', async () => {
    const _vm = vm.$refs['typeahead-match-start']
    _vm.matchStart = true
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'ala'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(2)
  })

  it('should be able to use async typeahead', async () => {
    const _vm = vm.$refs['typeahead-async-query']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    // matches don't work in here
    const savedMatches = Element.prototype.matches
    Element.prototype.matches = () => true
    input.value = 'wxsm'
    utils.triggerEvent(input, 'input')
    await utils.sleep(600)
    server.requests[0].respond(
      200,
      {'Content-Type': 'application/json'},
      JSON.stringify({items: [{login: 'wxsms'}]})
    )
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(1)
    const selected = dropdown.querySelector('li.active a span')
    expect(selected.textContent).to.equal('wxsms')
    Element.prototype.matches = savedMatches
  })

  it('should be able to use component target', async () => {
    const res = Vue.compile('
' +
      '<collapse ref="input"/>' +
      '<typeahead ref="typeahead" :target="ele" v-model="model"></typeahead>' +
      '
')
    const vm = new Vue({
      data () {
        return {
          ele: null,
          model: null
        }
      },
      mounted () {
        this.ele = this.$refs.input
      },
      render: res.render,
      staticRenderFns: res.staticRenderFns
    })
    vm.$mount()
    await vm.$nextTick()
    expect(vm.$refs.typeahead.inputEl).to.equal(vm.ele.$el)
    vm.$destroy()
  })

  it('should be ok if target invalid', async () => {
    const res = Vue.compile('
' +
      '<typeahead ref="typeahead" :target="ele" v-model="model"></typeahead>' +
      '
')
    const vm = new Vue({
      data () {
        return {
          ele: {a: 1},
          model: null
        }
      },
      render: res.render,
      staticRenderFns: res.staticRenderFns
    })
    vm.$mount()
    await vm.$nextTick()
    expect(vm.$refs.typeahead.inputEl).to.be.null
    vm.$destroy()
  })

  it('should be able to use string arr async returns', async () => {
    const res = Vue.compile('
' +
      '<input ref="input">' +
      '<typeahead :target="ele" v-model="model" async-src="https://api.github.com/search/users?q="></typeahead>' +
      '
')
    const vm = new Vue({
      data () {
        return {
          ele: null,
          model: null
        }
      },
      mounted () {
        this.ele = this.$refs.input
      },
      render: res.render,
      staticRenderFns: res.staticRenderFns
    })
    vm.$mount()
    await vm.$nextTick()
    const input = vm.$el.querySelector('input')
    const dropdown = vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    // matches don't work in here
    const savedMatches = Element.prototype.matches
    Element.prototype.matches = () => true
    input.value = 'a'
    utils.triggerEvent(input, 'input')
    await utils.sleep(600)
    server.requests[1].respond(
      200,
      {'Content-Type': 'application/json'},
      JSON.stringify(['aa', 'ab', 'ac'])
    )
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(3)
    const selected = dropdown.querySelector('li.active a span')
    expect(selected.textContent).to.equal('aa')
    Element.prototype.matches = savedMatches
    vm.$destroy()
  })

  it('should be able to handel async typeahead error', async () => {
    const res = Vue.compile('
' +
      '<input ref="input">' +
      '<typeahead @loaded-error="onErr" :target="ele" v-model="model" async-src="https://api.github.com/search/users?q="></typeahead>' +
      '
')
    const vm = new Vue({
      data () {
        return {
          ele: null,
          model: null,
          err: null
        }
      },
      mounted () {
        this.ele = this.$refs.input
      },
      methods: {
        onErr () {
          this.err = 'error'
        }
      },
      render: res.render,
      staticRenderFns: res.staticRenderFns
    })
    vm.$mount()
    await vm.$nextTick()
    expect(vm.err).not.exist
    const input = vm.$el.querySelector('input')
    const dropdown = vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    // matches don't work in here
    const savedMatches = Element.prototype.matches
    Element.prototype.matches = () => true
    input.value = 'wxsm'
    utils.triggerEvent(input, 'input')
    await utils.sleep(600)
    server.requests[2].respond(
      500,
      {'Content-Type': 'application/json'},
      JSON.stringify([{id: 1, text: 'Provide examples', done: true}])
    )
    await vm.$nextTick()
    expect(dropdown.className).to.not.contain('open')
    expect(vm.err).to.exist
    Element.prototype.matches = savedMatches
    vm.$destroy()
  })

  it('should be able to bind string data', async () => {
    const res = Vue.compile('
' +
      '<input ref="input">' +
      '<typeahead :ignore-case="false" :target="ele" :data="data" v-model="model"></typeahead>' +
      '
')
    const vm = new Vue({
      data () {
        return {
          data: ['aa', 'ab', 'bb'],
          ele: null,
          model: null
        }
      },
      mounted () {
        this.ele = this.$refs.input
      },
      render: res.render,
      staticRenderFns: res.staticRenderFns
    })
    vm.$mount()
    await vm.$nextTick()
    const input = vm.$el.querySelector('input')
    const dropdown = vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'a'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(2)
    const selected = dropdown.querySelector('li.active a')
    expect(selected.textContent).to.equal('aa')
    selected.click()
    await vm.$nextTick()
    expect(vm.model).to.equal('aa')
    expect(input.value).to.equal('aa')
    vm.model = 'bb'
    await vm.$nextTick()
    expect(vm.model).to.equal('bb')
    expect(input.value).to.equal('bb')
    vm.$destroy()
  })

  it('should be able to disable preselect', async () => {
    const res = Vue.compile('
' +
      '<input ref="input">' +
      '<typeahead :preselect="false" :target="ele" :data="data" v-model="model"></typeahead>' +
      '
')
    const vm = new Vue({
      data () {
        return {
          data: ['aa', 'ab', 'bb'],
          ele: null,
          model: ''
        }
      },
      mounted () {
        this.ele = this.$refs.input
      },
      render: res.render,
      staticRenderFns: res.staticRenderFns
    })
    vm.$mount()
    await vm.$nextTick()
    const input = vm.$el.querySelector('input')
    const dropdown = vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    input.value = 'a'
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(2)
    expect(dropdown.querySelector('li.active a')).not.exist
    utils.triggerKey(input, utils.keyCodes.enter)
    await vm.$nextTick()
    expect(dropdown.className).to.not.contain('open')
    expect(vm.model).to.equal('a')
    expect(input.value).to.equal('a')
    utils.triggerEvent(input, 'input')
    await vm.$nextTick()
    utils.triggerKey(input, utils.keyCodes.down)
    await vm.$nextTick()
    expect(dropdown.querySelector('li.active a')).to.exist
    expect(dropdown.querySelector('li.active a').textContent).to.equal('aa')
    dropdown.querySelector('li.active a').click()
    await vm.$nextTick()
    expect(vm.model).to.equal('aa')
    expect(input.value).to.equal('aa')
    expect(dropdown.className).to.not.contain('open')
    vm.$destroy()
  })

  it('should be able to use async-function and custom template', async () => {
    const _vm = vm.$refs['typeahead-custom-template']
    await vm.$nextTick()
    const input = _vm.$el.querySelector('input')
    const dropdown = _vm.$el.querySelector('.dropdown')
    expect(dropdown.className).to.not.contain('open')
    // matches don't work in here
    const savedMatches = Element.prototype.matches
    Element.prototype.matches = () => true
    input.value = 'wxsm'
    utils.triggerEvent(input, 'input')
    await utils.sleep(600)
    server.requests[3].respond(
      200,
      {'Content-Type': 'application/json'},
      JSON.stringify({items: [{login: 'wxsms'}]})
    )
    await vm.$nextTick()
    expect(dropdown.className).to.contain('open')
    expect(dropdown.querySelectorAll('li').length).to.equal(1)
    const selected = dropdown.querySelector('li.active a span')
    expect(selected.textContent).to.equal('wxsms')
    Element.prototype.matches = savedMatches
  })
})


text:
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  TouchableNativeFeedback,
  Image,
  TouchableOpacity,
  Platform,
} from 'react-native';
import Communications from 'react-native-communications';

export default class ChooseSearch extends Component {
    constructor(props) {
        super(props);
        this._onGoFindAClub = this._onGoFindAClub.bind(this);
        this._onGoFindAnEvent = this._onGoFindAnEvent.bind(this);
    }

    render() {
        return (
            <View style={{backgroundColor: '#F5FCFF', marginTop: 40}}>
                <Text style={styles.title}>Which would you like to search?</Text>

                <View style={{flex: 1, flexDirection: 'row', justifyContent: 'space-around', paddingLeft: 10}}>
                    <Image style={styles.pictures} source={require('./images/Club-Icon.png')} />
                    <Image style={styles.pictures} source={require('./images/Events-Icon.png')} />
                </View>

                <View style={{width: 365, height: 100, flexDirection: 'row', justifyContent: 'space-around', paddingLeft: 13, paddingTop: 75}}>
                    <TouchableHighlight onPress={()=>this._onGoFindAClub()}><Text style={styles.subtitles}>Search Clubs</Text></TouchableHighlight>
                    <TouchableHighlight onPress={()=>this._onGoFindAnEvent()}><Text style={styles.subtitles}>Search Events</Text></TouchableHighlight>
                </View>
            </View>
        );
    }

    _onGoFindAClub() {
        this.props.navigator.push({
            type: "findaclub",
            index: this.props.route.index+1,
            state: this.props.route.state
        });
    }

    _onGoFindAnEvent() {
        this.props.navigator.push({
            type: "findanevent",
            index: this.props.route.index+1,
            state: this.props.route.state
        });
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },

    options: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        backgroundColor: '#F5FCFF',
    },

    icons: {
        flex: 1,
        flexDirection: 'column',
        height: 100,
        width: 100,
        justifyContent: 'space-between',
        backgroundColor: '#F5FCFF',
    },

    pictures: {
        height: 80,
        width: 80,
    },

    subtitles: {
        fontSize: 15,
        color: '#800000',
        fontWeight: 'bold',
    },

    title: {
        ...Platform.select({
            android: {textAlign: 'center'},
        }),
        fontWeight: 'bold',
        color: '#800000',
        fontSize: 20,
        paddingTop: 50,
        paddingBottom: 50,
    },
});


text:
<?php

namespace Google\Service\Document;

class GoogleCloudDocumentaiV1beta2ProcessDocumentResponse extends \Google\Model
{
  protected $inputConfigType = GoogleCloudDocumentaiV1beta2InputConfig::class;
  protected $inputConfigDataType = '';
  protected $outputConfigType = GoogleCloudDocumentaiV1beta2OutputConfig::class;
  protected $outputConfigDataType = '';

  /**
   * @param GoogleCloudDocumentaiV1beta2InputConfig
   */
  public function setInputConfig(GoogleCloudDocumentaiV1beta2InputConfig $inputConfig)
  {
    $this->inputConfig = $inputConfig;
  }
  /**
   * @return GoogleCloudDocumentaiV1beta2InputConfig
   */
  public function getInputConfig()
  {
    return $this->inputConfig;
  }
  /**
   * @param GoogleCloudDocumentaiV1beta2OutputConfig
   */
  public function setOutputConfig(GoogleCloudDocumentaiV1beta2OutputConfig $outputConfig)
  {
    $this->outputConfig = $outputConfig;
  }
  /**
   * @return GoogleCloudDocumentaiV1beta2OutputConfig
   */
  public function getOutputConfig()
  {
    return $this->outputConfig;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudDocumentaiV1beta2ProcessDocumentResponse::class, 'Google_Service_Document_GoogleCloudDocumentaiV1beta2ProcessDocumentResponse');


text:
package com.android.example.text.styling.renderer.spans;

import static junit.framework.Assert.assertEquals;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.graphics.Typeface;
import android.text.TextPaint;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

/**
 * Tests for the {@link FontSpan} class
 */
public class FontSpanTest {

    private TextPaint paint = mock(TextPaint.class);
    private FontSpan span = new FontSpan(Typeface.DEFAULT);
    private Typeface defaultTypeface = Typeface.create("serif", Typeface.BOLD);

    @Before
    public void setUp() {
        when(paint.getTypeface()).thenReturn(defaultTypeface);
    }

    @Test
    public void updateMeasureState() {
        // When the update measure state is called
        span.updateMeasureState(paint);

        // Check that the typeface set has the correct typeface and style
        ArgumentCaptor<Typeface> captor = ArgumentCaptor.forClass(Typeface.class);
        verify(paint).setTypeface(captor.capture());
        assertEquals(Typeface.BOLD, captor.getValue().getStyle());
    }

    @Test
    public void updateDrawState() {
        // When the update draw state is called
        span.updateDrawState(paint);

        // Check that the typeface set has the correct typeface and style
        ArgumentCaptor<Typeface> captor = ArgumentCaptor.forClass(Typeface.class);
        verify(paint).setTypeface(captor.capture());
        assertEquals(Typeface.BOLD, captor.getValue().getStyle());
    }

}


text:
<!DOCTYPE html>

<TITLE>Manpage of MBIND</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

MBIND

Section: Linux Programmer's Manual (2)
Updated: 2008-08-15
Index
Return to Main Contents

NAME

mbind - Set memory policy for a memory range

SYNOPSIS

#include <numaif.h>

int mbind(void *addr, unsigned long len, int mode,
          unsigned long *nodemask, unsigned long maxnode,
          unsigned flags);

Link with -lnuma.

DESCRIPTION

mbind()

sets the NUMA memory policy,
which consists of a policy mode and zero or more nodes,
for the memory range starting with
addr

and continuing for
len

bytes.
The memory policy defines from which node memory is allocated.

If the memory range specified by the
addr and len

arguments includes an "anonymous" region of memory---that is
a region of memory created using the
mmap(2)

system call with the
MAP_ANONYMOUS---or

a memory mapped file, mapped using the
mmap(2)

system call with the
MAP_PRIVATE

flag, pages will only be allocated according to the specified
policy when the application writes [stores] to the page.
For anonymous regions, an initial read access will use a shared
page in the kernel containing all zeros.
For a file mapped with
MAP_PRIVATE,

an initial read access will allocate pages according to the
process policy of the process that causes the page to be allocated.
This may not be the process that called
mbind().

The specified policy will be ignored for any
MAP_SHARED

mappings in the specified memory range.
Rather the pages will be allocated according to the process policy
of the process that caused the page to be allocated.
Again, this may not be the process that called
mbind().

If the specified memory range includes a shared memory region
created using the
shmget(2)

system call and attached using the
shmat(2)

system call,
pages allocated for the anonymous or shared memory region will
be allocated according to the policy specified, regardless which
process attached to the shared memory segment causes the allocation.
If, however, the shared memory region was created with the
SHM_HUGETLB

flag,
the huge pages will be allocated according to the policy specified
only if the page allocation is caused by the process that calls
mbind()

for that region.

By default,
mbind()

only has an effect for new allocations; if the pages inside
the range have been already touched before setting the policy,
then the policy has no effect.
This default behavior may be overridden by the
MPOL_MF_MOVE

and
MPOL_MF_MOVE_ALL

flags described below.

The
mode

argument must specify one of
MPOL_DEFAULT,

MPOL_BIND,

MPOL_INTERLEAVE

or
MPOL_PREFERRED.

All policy modes except
MPOL_DEFAULT

require the caller to specify via the
nodemask

argument,
the node or nodes to which the mode applies.

The
mode

argument may also include an optional
mode flag .

The supported
mode flags

are:

MPOL_F_STATIC_NODES (since Linux-2.6.26)

A non-empty
nodemask

specifies physical node ids.
Linux does not remap the
nodemask

when the process moves to a different cpuset context,
nor when the set of nodes allowed by the process's
current cpuset context changes.

MPOL_F_RELATIVE_NODES (since Linux-2.6.26)

A non-empty
nodemask

specifies node ids that are relative to the set of
node ids allowed  by the process's current cpuset.

nodemask

points to a bitmask of nodes containing up to
maxnode

bits.
The bit mask size is rounded to the next multiple of
sizeof(unsigned long),

but the kernel will only use bits up to
maxnode.

A NULL value of
nodemask

or a
maxnode

value of zero specifies the empty set of nodes.
If the value of
maxnode

is zero,
the
nodemask

argument is ignored.
Where a
nodemask

is required, it must contain at least one node that is on-line,
allowed by the process's current cpuset context
[unless the
MPOL_F_STATIC_NODES

mode flag is specified],
and contains memory.

The
MPOL_DEFAULT

mode requests that any non-default policy be removed,
restoring default behavior.
When applied to a range of memory via
mbind(),

this means to use the process policy,
which may have been set with
set_mempolicy(2).

If the mode of the process policy is also
MPOL_DEFAULT,

the system-wide default policy will be used.
The system-wide default policy allocates
pages on the node of the CPU that triggers the allocation.
For
MPOL_DEFAULT,

the
nodemask

and
maxnode

arguments must be specify the empty set of nodes.

The
MPOL_BIND

mode specifies a strict policy that restricts memory allocation to
the nodes specified in
nodemask.

If
nodemask

specifies more than one node, page allocations will come from
the node with the lowest numeric node ID first, until that node
contains no free memory.
Allocations will then come from the node with the next highest
node ID specified in
nodemask

and so forth, until none of the specified nodes contain free memory.
Pages will not be allocated from any node not specified in the
nodemask.

The
MPOL_INTERLEAVE

mode specifies that page allocations be interleaved across the
set of nodes specified in
nodemask.

This optimizes for bandwidth instead of latency
by spreading out pages and memory accesses to those pages across
multiple nodes.
To be effective the memory area should be fairly large,
at least 1MB or bigger with a fairly uniform access pattern.
Accesses to a single page of the area will still be limited to
the memory bandwidth of a single node.

MPOL_PREFERRED

sets the preferred node for allocation.
The kernel will try to allocate pages from this
node first and fall back to other nodes if the
preferred nodes is low on free memory.
If
nodemask

specifies more than one node ID, the first node in the
mask will be selected as the preferred node.
If the
nodemask

and
maxnode

arguments specify the empty set, then the memory is allocated on
the node of the CPU that triggered the allocation.
This is the only way to specify "local allocation" for a
range of memory via
mbind().

If
MPOL_MF_STRICT

is passed in
flags

and
policy

is not
MPOL_DEFAULT,

then the call will fail with the error
EIO

if the existing pages in the memory range don't follow the policy.

If
MPOL_MF_MOVE

is specified in
flags,

then the kernel will attempt to move all the existing pages
in the memory range so that they follow the policy.
Pages that are shared with other processes will not be moved.
If
MPOL_MF_STRICT

is also specified, then the call will fail with the error
EIO

if some pages could not be moved.

If
MPOL_MF_MOVE_ALL

is passed in
flags,

then the kernel will attempt to move all existing pages in the memory range
regardless of whether other processes use the pages.
The calling process must be privileged
(CAP_SYS_NICE)

to use this flag.
If
MPOL_MF_STRICT

is also specified, then the call will fail with the error
EIO

if some pages could not be moved.

RETURN VALUE

On success,
mbind()

returns 0;
on error, -1 is returned and
errno

is set to indicate the error.

ERRORS

EFAULT

Part or all of the memory range specified by
nodemask

and
maxnode

points outside your accessible address space.
Or, there was an unmapped hole in the specified memory range.

EINVAL

An invalid value was specified for
flags

or
mode;

or
addr + len

was less than
addr;

or
addr

is not a multiple of the system page size.
Or,
mode

is
MPOL_DEFAULT

and
nodemask

specified a non-empty set;
or
mode

is
MPOL_BIND

or
MPOL_INTERLEAVE

and
nodemask

is empty.
Or,
maxnode

exceeds a kernel-imposed limit.

Or,
nodemask

specifies one or more node IDs that are
greater than the maximum supported node ID.
Or, none of the node IDs specified by
nodemask

are on-line and allowed by the process's current cpuset context,
or none of the specified nodes contain memory.
Or, the
mode

argument specified both
MPOL_F_STATIC_NODES

and
MPOL_F_RELATIVE_NODES.

EIO

MPOL_MF_STRICT

was specified and an existing page was already on a node
that does not follow the policy;
or
MPOL_MF_MOVE

or
MPOL_MF_MOVE_ALL

was specified and the kernel was unable to move all existing
pages in the range.

ENOMEM

Insufficient kernel memory was available.

EPERM

The
flags

argument included the
MPOL_MF_MOVE_ALL

flag and the caller does not have the
CAP_SYS_NICE

privilege.

VERSIONS

The
mbind(),

system call was added to the Linux kernel in version 2.6.7.

CONFORMING TO

This system call is Linux-specific.

NOTES

For information on library support, see
numa(7).

NUMA policy is not supported on a memory mapped file range
that was mapped with the
MAP_SHARED

flag.

The
MPOL_DEFAULT

mode can have different effects for
mbind()

and
set_mempolicy(2).

When
MPOL_DEFAULT

is specified for
set_mempolicy(2),

the process's policy reverts to system default policy
or local allocation.
When
MPOL_DEFAULT

is specified for a range of memory using
mbind(),

any pages subsequently allocated for that range will use
the process's policy, as set by
set_mempolicy(2).

This effectively removes the explicit policy from the
specified range, "falling back" to a possibly non-default
policy.
To select explicit "local allocation" for a memory range,
specify a
mode

of
MPOL_PREFERRED

with an empty set of nodes.
This method will work for
set_mempolicy(2),

as well.

Support for huge page policy was added with 2.6.16.
For interleave policy to be effective on huge page mappings the
policied memory needs to be tens of megabytes or larger.

MPOL_MF_STRICT

is ignored on huge page mappings.

MPOL_MF_MOVE

and
MPOL_MF_MOVE_ALL

are only available on Linux 2.6.16 and later.

SEE ALSO

get_mempolicy(2),

getcpu(2),

mmap(2),

set_mempolicy(2),

shmat(2),

shmget(2),

numa(3),

cpuset(7),

numa(7),

numactl(8)

COLOPHON

This page is part of release 3.22 of the Linux
man-pages

project.
A description of the project,
and information about reporting bugs,
can be found at
http://www.kernel.org/doc/man-pages/.

Index

NAME

SYNOPSIS

DESCRIPTION

RETURN VALUE

ERRORS

VERSIONS

CONFORMING TO

NOTES

SEE ALSO

COLOPHON

This document was created by
man2html,
using the manual pages.

Time: 05:33:04 GMT, December 24, 2015


text:
--
-- Table structure for table `res_engine`
--

CREATE TABLE IF NOT EXISTS `res_engine` (
  `id` char(12) CHARACTER SET ascii NOT NULL,
  PRIMARY KEY (`id`)
);

--
-- Dumping data for table `res_engine`
--

INSERT INTO `res_engine` (`id`) VALUES
('menu'),
('static'),
('status')
ON DUPLICATE KEY UPDATE `id`=`id`;

-- --------------------------------------------------------

--
-- Table structure for table `res_extension`
--

CREATE TABLE IF NOT EXISTS `res_extension` (
  `ext` char(6) CHARACTER SET ascii NOT NULL,
  `format` char(6) CHARACTER SET ascii DEFAULT NULL,
  `action_type` enum('static','dynamic','active') COLLATE utf8_spanish_ci NOT NULL,
  PRIMARY KEY (`ext`),
  KEY `format` (`format`)
);

--
-- Dumping data for table `res_extension`
--

INSERT INTO `res_extension` (`ext`, `format`, `action_type`) VALUES
('cgi', 'html', 'active'),
('csv', 'csv', 'dynamic'),
('exe', 'html', 'active'),
('htm', 'html', 'static'),
('html', 'html', 'static'),
('json', 'json', 'dynamic'),
('odf', 'odf', 'static'),
('odf!', 'odf', 'dynamic'),
('pdf', 'pdf', 'static'),
('pdf!', 'pdf', 'dynamic'),
('php', 'html', 'dynamic'),
('rss', 'rss', 'dynamic'),
('text', 'txt', 'static'),
('txt', 'txt', 'static'),
('txt!', 'txt', 'dynamic'),
('xhtml', 'html', 'static'),
('xml', 'xml', 'dynamic')
ON DUPLICATE KEY UPDATE `ext`=`ext`;

-- --------------------------------------------------------

--
-- Table structure for table `res_format`
--

CREATE TABLE IF NOT EXISTS `res_format` (
  `id` char(4) CHARACTER SET ascii NOT NULL,
  `mime_type` char(40) CHARACTER SET ascii DEFAULT NULL,
  `description` char(40) COLLATE utf8_spanish_ci DEFAULT NULL,
  `static` char(6) CHARACTER SET ascii DEFAULT NULL,
  `dynamic` char(6) CHARACTER SET ascii DEFAULT NULL,
  `active` char(6) CHARACTER SET armscii8 DEFAULT NULL,
  PRIMARY KEY (`id`)
);

--
-- Dumping data for table `res_format`
--

INSERT INTO `res_format` (`id`, `mime_type`, `description`, `static`, `dynamic`, `active`) VALUES
('csv', 'text/csv', 'Comma Separated Vector', NULL, 'csv', NULL),
('html', 'text/html', 'HTML page', 'html', 'php', 'cgi'),
('json', 'application/json', 'JSON data', NULL, 'json', NULL),
('odf', 'application/odf', 'ODF document', 'odf', 'odf!', NULL),
('pdf', 'application/pdf', 'PDF document', 'pdf', 'pdf!', NULL),
('rss', 'application/xml+rss', 'RSS feed', NULL, 'rss', NULL),
('txt', 'text/plain', 'Text file', 'txt', 'txt!', NULL),
('xml', 'application/xml', 'XML document', NULL, 'xml', NULL)
ON DUPLICATE KEY UPDATE `id`=`id`;

-- --------------------------------------------------------

--
-- Table structure for table `res_rel`
--

CREATE TABLE IF NOT EXISTS `res_rel` (
  `for` bigint(20) NOT NULL,
  `to` bigint(20) NOT NULL,
  `rel` enum('child','next') COLLATE utf8_spanish_ci NOT NULL
);

-- --------------------------------------------------------

--
-- Table structure for table `res_section`
--

CREATE TABLE IF NOT EXISTS `res_section` (
  `id` char(12) CHARACTER SET ascii NOT NULL,
  `case` char(32) COLLATE utf8_spanish_ci DEFAULT NULL,
  `priority` tinyint(1) DEFAULT NULL,
  `description` char(40) COLLATE utf8_spanish_ci DEFAULT NULL,
  `engine` char(20) CHARACTER SET ascii DEFAULT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `res_section` (`id`, `case`, `priority`, `description`, `engine`) VALUES
('menu', '(menu)/(\\w*)', 1, 'menu', 'menu'),
('root', '()(.*)', 0, 'root static content', 'static'),
('status', '(status)/(\\d{3})', 1, 'http status messages', 'status')
ON DUPLICATE KEY UPDATE `id`=`id`;


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <!--
        <service
            id="twig.extension.content_mongodb_extension"
            class="AntiMattr\Bundle\ContentMongoDBBundle\Twig\Extension\ContentMongoDBExtension">

            <tag name="twig.extension" />
            <argument type="service" id="service_container" />
        </service>
        -->
        <service
            id="antimattr.content_mongodb_manager"
            class="AntiMattr\Bundle\ContentMongoDBBundle\Service\ContentMongoDBManager">

            <argument type="service" id="doctrine_mongodb.odm.default_document_manager" />
        </service>
    </services>
</container>


text:
DROP TABLE address;
DROP TABLE broker;
DROP TABLE brokerworksfor;
DROP TABLE client;
DROP TABLE company;
DROP TABLE stockbooklist;
DROP TABLE stockinformation;
DROP TABLE transaction;


text:
package com.appleframework.data.hbase.client.service.basicService.hql;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import junit.framework.Assert;

import org.junit.Test;

import com.appleframework.data.hbase.myrecord.MyRecord;
import com.appleframework.data.hbase.myrecord.MyRecordRowKey;
import com.appleframework.data.hbase.myrecord.MyRecordTestBase;

/**
 * @author xinzhi
 */

@SuppressWarnings("deprecation")
public class TestLessEqual extends MyRecordTestBase {

    @Test
    public void testConstants() {
        putSlim("id=0,name=aaa");
        putSlim("id=1,name=bbb");
        putSlim("id=2,name=ccc");

        addHql("select where name lessequal \"aaa\"");
        List<MyRecord> myRecordList = simpleHbaseClient.findObjectList(
                new MyRecordRowKey(0), new MyRecordRowKey(100), MyRecord.class,
                TestHqlId, null);
        Assert.assertTrue(myRecordList.size() == 1);

        addHql("select where name lessequal \"bbb\"");
        myRecordList = simpleHbaseClient.findObjectList(new MyRecordRowKey(0),
                new MyRecordRowKey(100), MyRecord.class, TestHqlId, null);
        Assert.assertTrue(myRecordList.size() == 2);

        addHql("select where name lessequal \"ccc\"");
        myRecordList = simpleHbaseClient.findObjectList(new MyRecordRowKey(0),
                new MyRecordRowKey(100), MyRecord.class, TestHqlId, null);
        Assert.assertTrue(myRecordList.size() == 3);

        addHql("select where name lessequal \"ddd\"");
        myRecordList = simpleHbaseClient.findObjectList(new MyRecordRowKey(0),
                new MyRecordRowKey(100), MyRecord.class, TestHqlId, null);
        Assert.assertTrue(myRecordList.size() == 3);

    }

    @Test
    public void testVar() {
        putSlim("id=0,name=aaa");
        putSlim("id=1,name=bbb");
        putSlim("id=2,name=ccc");

        addHql("select where name lessequal #name#");
        Map<String, Object> para = new HashMap<String, Object>();

        para.put("name", "aaa");
        List<MyRecord> myRecordList = simpleHbaseClient.findObjectList(
                new MyRecordRowKey(0), new MyRecordRowKey(100), MyRecord.class,
                TestHqlId, para);
        Assert.assertTrue(myRecordList.size() == 1);

        para.put("name", "bbb");
        myRecordList = simpleHbaseClient.findObjectList(new MyRecordRowKey(0),
                new MyRecordRowKey(100), MyRecord.class, TestHqlId, para);
        Assert.assertTrue(myRecordList.size() == 2);

        para.put("name", "ccc");
        myRecordList = simpleHbaseClient.findObjectList(new MyRecordRowKey(0),
                new MyRecordRowKey(100), MyRecord.class, TestHqlId, para);
        Assert.assertTrue(myRecordList.size() == 3);

        para.put("name", "ddd");
        myRecordList = simpleHbaseClient.findObjectList(new MyRecordRowKey(0),
                new MyRecordRowKey(100), MyRecord.class, TestHqlId, para);
        Assert.assertTrue(myRecordList.size() == 3);

    }

}


text:
// Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.

package jodd.joy.db;

import jodd.db.oom.sqlgen.DbEntitySql;
import static jodd.db.oom.sqlgen.DbEntitySql.insert;
import static jodd.db.oom.sqlgen.DbEntitySql.updateAll;
import static jodd.db.oom.sqlgen.DbEntitySql.findByColumn;
import static jodd.db.oom.DbOomQuery.query;
import jodd.db.DbQuery;
import jodd.petite.meta.PetiteBean;
import jodd.petite.meta.PetiteInject;
import jodd.log.Logger;
import jodd.log.LoggerFactory;

import java.util.List;

/**
 * Generic DAO.
 */
@PetiteBean
public class AppDao {

	private static final Logger log = LoggerFactory.getLogger(AppDao.class);

	@PetiteInject
	DbIdGenerator dbIdGenerator;

	public AppDao() {
		setGeneratedKeys(true);
	}

	// ---------------------------------------------------------------- config

	protected boolean generatedKeys;

	/**
	 * Returns true if keys should be auto-generated.
	 */
	public boolean isGeneratedKeys() {
		return generatedKeys;
	}

	/**
	 * Specifies how primary keys are generated.
	 */
	public void setGeneratedKeys(boolean generatedKeys) {
		this.generatedKeys = generatedKeys;
		if (log.isDebugEnabled()) {
			if (generatedKeys) {
				log.debug("IDs are incremented in database");
			} else {
				log.debug("IDs are generated by DbIdGenerator");
			}
		}
	}

	// ---------------------------------------------------------------- store

	/**
	 * Saves or updates entity. If ID is not null, entity will be updated.
	 * Otherwise, entity will be inserted into the database.
	 */
	public <E extends Entity> E store(E entity) {
		if (entity.isPersistent() == false) {
			DbQuery q;
			if (generatedKeys == true) {
				q = query(insert(entity));
				q.setGeneratedKey();
				q.executeUpdate();
				long key = q.getGeneratedKey();
				entity.setEntityId(key);
			} else {
				long nextId = dbIdGenerator.nextId(entity);
				entity.setEntityId(nextId);
				q = query(insert(entity));
				q.executeUpdate();
			}
			q.close();
		} else {
			query(updateAll(entity)).executeUpdateAndClose();
		}
		return entity;
	}

	/**
	 * Simply saves entity into the database.
	 */
	public <E extends Entity> void save(E entity) {
		DbQuery q = query(insert(entity));
		q.executeUpdateAndClose();
	}

	// ---------------------------------------------------------------- update

	/**
	 * Finds single entity by its id.
	 */
	public <E extends Entity> E findById(Class<E> entityType, long id) {
		return query(DbEntitySql.findById(entityType, Long.valueOf(id))).findAndClose(entityType);
	}

	/**
	 * Updates single property.
	 */
	public <E extends Entity> void updateProperty(E entity, String name, Object value) {
		query(DbEntitySql.updateColumn(entity, name, value)).executeUpdateAndClose();
	}

	// ---------------------------------------------------------------- find

	/**
	 * Finds single entity by its id.
	 */
	@SuppressWarnings({"unchecked"})
	public <E extends Entity> E findById(E entity) {
		if (entity == null) {
			return null;
		}
		return (E) query(DbEntitySql.findById(entity)).findAndClose(entity.getClass());
	}

	/**
	 * Finds single entity by property match,
	 */
	public <E extends Entity> E findOneByProperty(Class<E> entityType, String name, Object value) {
		return query(findByColumn(entityType, name, value)).findAndClose(entityType);
	}

	/**
	 * Finds one entity for given criteria.
	 */
	@SuppressWarnings({"unchecked"})
	public <E extends Entity> E findOne(E criteria) {
		return (E) query(DbEntitySql.find(criteria)).findAndClose(criteria.getClass());
	}

	/**
	 * Finds list of entities matching given criteria.
	 */
	@SuppressWarnings({"unchecked"})
	public <E extends Entity> List<E> find(E criteria) {
		return query(DbEntitySql.find(criteria)).listAndClose(criteria.getClass());
	}

	// ---------------------------------------------------------------- delete

	/**
	 * Deleted single entity by its id.
	 */
	public void deleteById(Class entityType, long id) {
		query(DbEntitySql.deleteById(entityType, Long.valueOf(id))).executeUpdateAndClose();
	}

	/**
	 * Delete single object by its id.
	 */
	public void deleteById(Entity entity) {
		if (entity != null && entity.isPersistent()) {
			query(DbEntitySql.delete(entity)).executeUpdateAndClose();
		}
	}

	// ---------------------------------------------------------------- count

	/**
	 * Counts number of entities.
	 */
	public <E extends Entity> long count(Class<E> entityType) {
		return query(DbEntitySql.count(entityType)).executeCountAndClose();
	}

	// ---------------------------------------------------------------- related

	/**
	 * Finds related entity.
	 */
	public <E extends Entity> List<E> findRelated(Class<E> target, Entity source) {
		return query(DbEntitySql.findForeign(target, source)).listAndClose();
	}

	// ---------------------------------------------------------------- list

	/**
	 * List all entities.
	 */
	public <E extends Entity> List<E> list(Class<E> target) {
		return query(DbEntitySql.from(target)).list(target);
	}

}


text:
Inspirational Quotes

Never frown, even when you are sad, because you never know who is falling in love with your smile.

纵然伤心,也不要愁眉不展,因为你不知是谁会爱上你的笑容。

The world won"t care about your self-esteem. The world will expect you to accomplish something before you feel good about yourself.

这世界并不会在意你的自尊。这世界指望你在自我感觉良好之前先要有所成就。

Maris

Design Project

Dictum

Sedvel Erat Non

Consectur Fusce Enim

Phasellus dapibus nulla quis risus auctor, non placerat augue consectetur.

Consectur Fusce Enim

Phasellus dapibus nulla quis risus auctor, non placerat augue consectetur.

User Table

                        No.
                        First Name
                        Last Name
                        Username

                        1.
                        wenqiang
                        Wei
                        @wQ

                        2.
                        junwei
                        Zhang
                        @jW

                        3.
                        pengfei
                        Wang
                        @pF

                        4.
                        zhijun
                        Ma
                        @zJ

                        5.
                        xiaokai
                        Zhang
                        @xK

Collect from �ֻ���վģ��

Modularnew

Interactivenew

Copyright © 2084 Company Name
            | More Templates 模板之家 - Collect from 网页模板


text:
<!DOCTYPE html>
<html>
<body>
<script src="../resources/js-test.js"></script>
<script>
description("Test multiple promise resolution.");

if (!window.testRunner)
    debug('This test cannot be run without the TestRunner');

// Clean-up any unused battery manager objects from previous tests.
gc();
jsTestIsAsync = true;
testRunner.waitUntilDone();
testRunner.setCanOpenWindows();
testRunner.setCloseRemainingWindowsWhenComplete(true);

var mockBatteryInfo;
function setAndFireMockBatteryInfo(charging, chargingTime, dischargingTime, level) {
    mockBatteryInfo = { charging: charging,
                        chargingTime: chargingTime,
                        dischargingTime: dischargingTime,
                        level: level };
    testRunner.didChangeBatteryStatus(charging, chargingTime, dischargingTime, level);
}

// compare obtained battery values with the mock values
function checkBatteryInfo(batteryManager) {
    batteryInfo = batteryManager;
    shouldBeDefined("batteryInfo");
    shouldBeDefined("mockBatteryInfo");
    shouldBe('batteryInfo.charging', 'mockBatteryInfo.charging');
    shouldBe('batteryInfo.chargingTime', 'mockBatteryInfo.chargingTime');
    shouldBe('batteryInfo.dischargingTime', 'mockBatteryInfo.dischargingTime');
    shouldBe('batteryInfo.level', 'mockBatteryInfo.level');
}

function batteryStatusFailure() {
    testFailed('failed to successfully resolve the promise');
    setTimeout(finishJSTest, 0);
}

var promise1Count = 0;
var promise2Count = 0;

function finishIfReady() {
    if (promise1Count == 1 && promise2Count == 1)
        setTimeout(finishJSTest, 0);
}

promise1 = navigator.getBattery();
promise1.then(
    function(battery) {
        debug('first resolution');
        checkBatteryInfo(battery);
        promise1Count++;
        finishIfReady();
    }, batteryStatusFailure);

promise2 = navigator.getBattery();
promise2.then(
    function(battery) {
        debug('second resolution');
        checkBatteryInfo(battery);
        promise2Count++;
        finishIfReady();
    }, batteryStatusFailure);

shouldBeTrue('promise1 === promise2');
setAndFireMockBatteryInfo(false, 10, 20, 0.5);
</script>
</body>
</html>


text:
#ifndef ARTCC_TASK_H
#define ARTCC_TASK_H

#include <iostream>
#include <string>
#include <utility>
#include <functional>

#include <log4cpp/Category.hh>

namespace artcc
{

class Task
{
private:
	int weight;
	std::string title;
    std::function<void()> taskProcess;
    unsigned int priority;
    unsigned int id;
    static log4cpp::Category& log;

    Task() = delete;

public:
	//Task(const int &, const std::string &);
    Task(const int &, const std::string &, std::function<void()>, const unsigned int & = 1);

	const unsigned int getWeight() const;
	void setWeight(const int &);

	const std::string getTitle() const;
	void setTitle(const std::string &);

    const unsigned int getPriority() const;
    void setPriority(const unsigned int &);

    void setTaskProcess(std::function<void()>);
    void runTask();
};

}

#endif


text:
template: page.html
title: Google Summer of Code Ideas
heading: Google Summer of Code Ideas
---

Here is a list of ideas for Google Summer of code projects. Feel free to submit your ideas.

If you are interested by one of these subjects, send a mail to vertx-enquiries@googlegroups.com. To submit your proposal, use the Eclipse Vert.x                organisation. Don't forget to read the tips at the end of this page. If you have questions, feel free to chat with us on IRC (freenode server, #vertx channel).

Prerequisites

Each year, we ask the students to prepare their GSOC application with a small project. This year (GSOC 2017), this project is a Twitter Wall. A Twitter Wall is a web page displaying the "latest" tweets. Everytime there is a new tweet, the wall is updated to display it.

 For this project, you need to create a Vert.x application using Vert.x Web, the SockJS bridge and the Vert.x Web client. You can also extend it with OAuth. You can also use a server side template engine if you want. You will host the source code of the project on GitHub and add a link to the repo in your application form. Don't forget to write a readme with the build and run instructions. All students willing to work on Vert.x during their GSOC must implement this project.

The twitter wall application:

retrieves tweets (matching configurable query) from Twitter using the Twitter API,

displays the tweets in a web page,

polls the API periodically (configurable) to update the tweets,

send the new tweets to the web page using the SockJS bridge,

update the displayed tweets on the web page dynamically (no reload of the page, consume the messages from the SockJS bridge).

If you have any questions, send a mail on the Vert.x Google Group.

Project Ideas (2017)

Developing a Vert.x based MQTT client

            Summary of idea:

Eclipse Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications. The project is about writing a native Vert.x MQTT client using the
              Netty library for handling all the network communications and the related MQTT codec for encoding/decoding the packets on the wire; it also means that an MQTT protocol state machine should be developed from scratch. The client should expose all
              the main features of MQTT clients as defined by the MQTT 3.1.1 spec.

            Knowledge prerequisite: Java (8), Maven, MQTT 3.1.1 spec is a plus

            Skill level: Intermediate, Experienced

            Contact(s) / potential mentors(s): ppatiern@redhat.com

Vert.x-Web purely functional handlers

            Summary of idea:

Eclipse Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications. Use any function as a vertx-web handler, then provide an API to compose
                these functions in a "RouterBuilder API" way. This should be a totally separated project, keeping vertx-web as is for now and targeting "pure JVM languages" (Java, Kotlin, Groovy, Scala), especially those who have "first-level" functions
                (and maybe annotations).

            What should be achieved:

any lambda can now be used as a vert.x web handler, automatically resolving lambda parameters.

provide the ability to deal with futures in vert.x-web, if a lambda is returning an AsyncResult, then:

the next handler should only be called once the future is completed.

the context should automatically been failed if the asyncresult is failed.

allow users to define custom parameters resolvers by implementing an interface such as Resolvable<RoutingContext, T> or AsyncResolvable<RoutingContext, T>.

create a "builder-like" API on top of vertx-web's Router to deal with such lambdas.

For further reference and examples see the following google group post.

            Knowledge prerequisite: Java (8), Gradle or Maven is a plus

            Skill level: Intermediate, Experienced

            Contact(s) / potential mentors(s): plopes@redhat.com, clement.escoffier@redhat.com

Vertx-Web implement HTTP standard responses logic to Router

            Summary of idea:

Eclipse Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications. Vert.x Web Router is a general purpose router that matches paths to handlers.
                Although this is "good enough" for many applications it does not adhere properly to the HTTP protocol. The issue is more obvious since the API allows filtering on mime type but failure to match such a request does not respect the protocol.

            Current inconsistent cases:

A router contains a route path but with misses the right HTTP verb, instead of returning 404 it should return 405.

A router contains a route for a specific mime type but the request contains a different payload mime type, instead of returning 404 it should return 406.

A router contains a route that produces a specific mime type but the request requires a different payload mime type, instead of returning 404 it should return 415.

An OPTIONS request should list the allowed verbs for the given path.

Errors thrown during path parameter parsing should throw 400 instead of 500.

The project should start with a review of the HTTP protocol including version 2 and identify faulty situations as described above. A proposal for a refactoring of the internal of the Router class while keeping the existing API is a must.

The code should be properly documented and easy to extend so later one can for example plug REST documentation generators, etc...

            Knowledge prerequisite: Java (8), Jenkins, Gradle or Maven is a plus

            Skill level: Intermediate, Experienced

            Contact(s) / potential mentors(s): plopes@redhat.com, clement.escoffier@redhat.com

Administration Console for Vert.x Applications

            Summary of idea:

Eclipse Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications. This topic is about implementing an extensible administration console.

The outcome should be able to be consumed as a Vert.x Web Handler, but also as guidelines to build such extensible dashboards.

            What should be achieved (non exhaustive list):

Scaffolding the dashboard

Provide a view of the application content

Provide a logger view to get and set the log levels

Add a basic monitoring view

Add a service discovery view

Add a circuit breaker view

Add a CRUD view

For further reference and examples see the following google group post.

            Knowledge prerequisite: Java (8), CSS, JavaScript Gradle or Maven is a plus

            Skill level: Intermediate, Experienced

            Contact(s) / potential mentors(s): plopes@redhat.com, clement.escoffier@redhat.com

Vert.x R language support

            Summary of idea:

Eclipse Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications. R is an open source programming language and software environment for
                statistical computing and graphics that is supported by the R Foundation for Statistical Computing. The R language is widely used among statisticians and data miners for developing statistical software and data analysis. Polls, surveys
                of data miners, and studies of scholarly literature databases show that R's popularity has increased substantially in recent years.

            What should be achieved:

Propose a vertx-lang-r using renjin

            Knowledge prerequisite: Java (8), MVEL, R

            Skill level: Intermediate, Experienced

            Contact(s) / potential mentors(s): plopes@redhat.com, clement.escoffier@redhat.com

Vert.x Certbot plugin

            Summary of idea:

Eclipse Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications.

Certbot is an easy-to-use automatic client that fetches and deploys SSL/TLS certificates for your webserver. Certbot was developed by EFF and others as a client for Let's Encrypt and was previously known
                as "the official Let's Encrypt client" or "the Let's Encrypt Python client." Certbot will also work with any other CAs that support the ACME protocol.

Certbot has several plugins for common web servers and can be used in manual mode with Vert.x too. This project would be about coding a new plugin for Certbot that would make the
                use of SSL certificates even easier for the Vert.x user community. The Certbot project is very open to new plugins and there is plenty of documentation. The project would be to follow the intructions from the link above and implement a
                tighter integration with Vert.x.

            What should be achieved:

Get acquainted with Certbot Python API

Writing a plugin for applications using Vert.x Core + Vert.x Web

Submit a PR

            Knowledge prerequisite: Python, Git

            Skill level: Intermediate

            Contact(s) / potential mentors(s): plopes@redhat.com, clement.escoffier@redhat.com

Vert.x on Embedded JDK

            Summary of idea:

Eclipse Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications. More and more Vert.x is getting used on IoT fields now that we offer
                support for MQTT and are lightweight when compared to other Java frameworks. It is important that Vert.x applications can run as expected under the embedded JDK using the compact profiles (JEP-161).

            What should be achieved:

Document how to work with Embedded JDK:

How to build and Vert.x application with a compact profile.

Identify if there are required changes to the core platform to cover this feature.

Write articles on this subject.

Work with the IoT community to identify usability issues and provide solutions.

            Knowledge prerequisite: Java (8)

            Skill level: Beginner, Intermediate

            Contact(s) / potential mentors(s): plopes@redhat.com, clement.escoffier@redhat.com

Previous ideas (2016)

Implementation of "blueprint" Vert.x applications

            Summary of idea:

Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications. The idea of the project is to implement a set of applications using the Vert.x
                toolkit to illustrate how different classes of applications can be done. This project aims to provide guidelines to Vert.x users to implement various applications.

The project starts with an introduction to Vert.x and the implementation of small examples using the different modules available in the Vert.x ecosystem. Then, the first application is a web application to manage a todo list following the
                specifications of Todo Backend. The second application is a message-based application such as Kue. The third application is also message-based but
                illustrates the scalability of Vert.x. It provides a message processing system able to handle a large number of message per seconds. Finally, the last application is a micro-service application close to the Spring Micro Service example.

Live demo of the applications will run on OpenShift and OpenStack, to illustrate production deployment. All these applications will be available and documented on the Vert.x website.

            Knowledge prerequisite: Java (8), Gradle or Maven is a plus

            Skill level: Beginner, Intermediate

            Contact(s) / potential mentors(s): plopes@redhat.com, clement.escoffier@redhat.com

            Associated JBoss community project(s): Vert.x

DevOps tooling for Vert.x applications

            Summary of idea:

Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications. The idea of the project is to implement a set of tools / guidelines to implement
                Vert.x using a "devops" approach. This cover continuous integration, continuous deployment, production settings and so on.

The project starts with an introduction to Vert.x and the implementation of small examples using the different modules available in the Vert.x ecosystem. In this project, you are going to:

provide the different settings to use different log aggregator that can be used with Vert.x application. This includes Graylog and Heka.

monitor applications based on New Relic, Netflix Servo are studied.

provide deployment recipes for Ansible and Chef

provide guidelines to implement continuous delivery of Vert.x application, in a zero-downtime environment

            Knowledge prerequisite: Java (8), Jenkins, Gradle or Maven is a plus

            Skill level: Intermediate, Experienced

            Contact(s) / potential mentors(s): clement.escoffier@redhat.com

            Associated JBoss community project(s): Vert.x, Ansible, Jenkins, Heka, Servo,...

Event bus clients for C, Objective-C, and Rust applications

            Summary of idea:

Vert.x is a toolkit for the Java Virtual Machine enabling the implementation of reactive, highly concurrent, polyglot applications. Thanks to its eventbus, any application can interact with Vert.x applications.
                The idea of the project is to provide a set of libraries to ease the integration of Vert.x applications with applications developed in Go, Rust and C.

The project starts with an introduction to Vert.x and the implementation of small examples using the different modules available in the Vert.x ecosystem. A focus is made on the integration capabilities and the event bus bridges.

At least 3 languages are covered in this project: C, Objective-C and Rust. Proposals for other languages are definitely welcome. For each language, a library is developed in order to let an application developed with the language to interact
                with the Vert.x Event Bus. The communication is based on TCP and JSON.

            Knowledge prerequisite: Java (8), some notion of C, Go and Rust

            Skill level: Intermediate, Experienced

            Contact(s) / potential mentors(s): plopes@redhat.com, jviet@redhat.com

            Associated JBoss community project(s): Vert.x, Rust


text:
import $ from 'jquery/jquery';

/**
 * Property Post.
 *
 * Using Select2.
 */
class Post {

  /**
   * Initialize Property Post.
   */
  static init() {
    new Post().binds();
  }

  /**
   * Bind elements with functions.
   */
  binds() {
    $(document).on('papi/property/repeater/added', '[data-property="post"]', this.update);
  }

  /**
   * Initialize pikaday field when added to repeater.
   *
   * @param {object} e
   */
  update(e) {
    e.preventDefault();

    const $select = $(this).parent().find('select');

    if ($select.hasClass('papi-component-select2') && 'select2' in $.fn) {
      $select.select2();
    }
  }

}

export default Post;


text:
package il.ac.technion.ie.measurements.utils;

import cern.colt.list.DoubleArrayList;
import cern.colt.list.IntArrayList;
import cern.colt.matrix.DoubleMatrix1D;

import java.util.BitSet;
import java.util.List;

/**
 * Created by I062070 on 18/06/2015.
 */
public class MeasurUtils {
    public static BitSet convertVectorToBitSet(DoubleMatrix1D matrix1D) {
        IntArrayList nonZeroIndices = new IntArrayList();
        matrix1D.getNonZeros(nonZeroIndices, new DoubleArrayList());

        BitSet bitSet = new BitSet(matrix1D.size());
        List<Integer> list = nonZeroIndices.toList();
        for (Integer index : list) {
            bitSet.set(index);
        }
        return bitSet;
    }
}


text:
/* global $:true */

require('../../styles/container/container.css');
require('../../styles/input-autocomplete/input-autocomplete');
require('../../styles/add-quest/add-quest');
require('../../styles/tags/tags');
require('../../styles/ymap/ymap');

$('#title, #city, #description, [name="image"], [name="title"], .location').on('blur', function () {
    if ($(this).val() === '') {
        $(this).addClass('input_error');
        $(this).attr('placeholder', 'Please enter ' + $(this).attr('id'));
    } else {
        $(this).removeClass('input_error');
    }

    var empty = false;

    $('input:required, textarea:required').each(function (idx, el) {
        var value = $(el).val();
        if (/^\s*$/.test(value)) {
            empty = true;
        }
    });

    if (empty) {
        $('button[role="createQuest"], button[role="editQuest"]').addClass('btn_disabled');
    } else {
        $('button[role="createQuest"], button[role="editQuest"]').removeClass('btn_disabled');
    }
});

$('button[role="editQuest"]').on('click', function () {
    if ($(this).hasClass('btn_disabled')) {
        return;
    }

    var tags = [];

    $('.tag').each(function (idx, el) {
        var tag = $(el).text().trim();
        tags.push(tag);
    });

    var msg = {};
    msg.title = $('#title').val();
    msg.description = $('#description').val();
    msg.city = $('#city').val();
    msg.slug = $('#slug').val();
    msg.tags = tags;

    $.ajax({
        type: 'POST',
        url: '/api/quests/' + msg.slug + '/edit', // SLUG
        data: msg,
        success: function ({data}) {
            $('.container').html('Квест успешно изменен');

            setTimeout(function () {
                window.location.href = '/quests/' + data.slug;
            }, 2000);
        },
        error: function () {
            $('.container').html('При изменении квеста произошла ошибка, попробуйте еще раз');

            setTimeout(function () {
                window.location.reload();
            }, 2000);
        }
    });
});

$('button[role="createQuest"]').on('click', function () {
    if ($(this).hasClass('btn_disabled')) {
        return;
    }

    var stagesForms = $('.quests-content .tab-content__panel');
    var tags = [];

    $('.tag').each(function (idx, el) {
        var tag = $(el).text().trim();
        tags.push(tag);
    });

    sendForm();

    function sendForm() {
        var msg = {};
        msg.title = $('#title').val();
        msg.description = $('#description').val();
        msg.city = $('#city').val();
        msg.tags = tags;

        $.ajax({
            type: 'POST',
            url: '/api/quests',
            data: msg,
            success: function (res) {
                var slug = res.data.slug;

                var promises = [];
                $(stagesForms).each(function (idx, el) {
                    $('.container').html('Квест успешно создан');
                    promises.push(sendStageForm(el, slug));
                });
                Promise.all(promises)
                    .then(function () {
                        setTimeout(function () {
                            window.location.href = '/quests/' + slug;
                        }, 1000);
                    });
            },
            error: function () {
                $('.container').html('При создании квеста произошла ошибка, попробуйте еще раз');

                setTimeout(function () {
                    window.location.reload();
                }, 2000);
            }
        });
    }

    function sendStageForm(form, slug) {
        var file = $(form).find('.add-quest__input[name="image"]')[0];
        var title = $(form).find('.title');
        var description = $(form).find('.description');
        var location = $(form).find('.location');
        var latitude = location.val().split(',')[0];
        var longitude = location.val().split(',')[1];

        var formData = new FormData();
        formData.append('image', file.files[0]);
        formData.append('title', title.val());
        formData.append('description', description.val());
        formData.append('lat', latitude);
        formData.append('lon', longitude);

        return new Promise(function (resolve, reject) {
            $.ajax({
                type: 'POST',
                url: '/api/quests/' + slug + '/stages',
                contentType: false,
                processData: false,
                data: formData,
                success: resolve,
                error: reject
            });
        });
    }
});

$('.quests-content').on('keyup', '.title', function () {
    var panel = $(this).closest('.tab-content__panel');
    var id = $(panel).attr('id');

    var tab = $('.tabs').find('a[href="#' + id + '"]');
    var val = $(this).val();
    if (/^\s*$/.test(val)) {
        $(tab).html('Без названия');
    } else {
        $(tab).html(val);
    }
});

$('.quests-content').on('click', '.add-quest_delete', function () {
    var tabContent = $(this).parent();

    var tabId = $(tabContent).attr('id');
    var tab = $('.add-quest__tabs').find('a[href="#' + tabId + '"]').parent();

    $(tab).remove();
    $(tabContent).remove();

    var newActiveTab = $('.add-quest__tabs').children();
    if (newActiveTab.length > 0) {
        $(newActiveTab[0]).find('.tabs__link').addClass('active');
    }

    var newActiveTabContent = $('.quests-content').children();
    if (newActiveTabContent.length > 0) {
        $(newActiveTabContent[0]).addClass('active');
    }
});


text:
<!doctype html>

    <title data-ng-bind="$state.current.name">
        worktracker
    </title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width">

    <link rel="stylesheet" href="bower_components/angular-xeditable/dist/css/xeditable.css">
    <link rel="stylesheet" type="text/css" href="bower_components/ng-grid/ng-grid.min.css">
    <link rel="stylesheet" type="text/css" href="bower_components/angular-ui-select/dist/select.min.css">
    <link rel="stylesheet" type="text/css" href="bower_components/angularjs-slider/dist/rzslider.min.css">
    <link rel="stylesheet" type="text/css" href="bower_components/selectize/dist/css/selectize.css">
    <link rel="stylesheet" type="text/css" href="bower_components/angular-chart.js/dist/angular-chart.css">

    <link rel="stylesheet" href="styles/bootstrap.css">
    <link rel="stylesheet" href="styles/animations.css">
    <link rel="stylesheet" href="styles/grid.css">
    <link rel="stylesheet" href="styles/main.css">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#main-navbar-collapse">
                Toggle navigation

            </button>

                worktracker

                     NAV.HOME

                     NAV.THEME

                     NAV.COMPONENTS

                     NAV.CHARTS

NAV.CURRENCIES


text:
import { padChars } from "../fp";
export = padChars;


text:
body{
  background: silver;
}

/* my name */
/* selector, property, value */
h1 {
  color : black;
}