text:
+++
title = "Número 202- Año XIV"
date = "1983-12-01"
numero = "202"

artistas = ["Robert Plant", "Danny Peyronel", "Riff", "Men At Work", "David Gilmour", "Pink Floyd", "The Animals", "Steavie Ray Vaughan", "Leonor Marchesi", "Púrpura", "Van Halen", "Barón Rojo", "Rubén Blades", "David Bowie", "Flashdance", "Manteniéndose vivo", "Ronnie Lane", "The Rolling Stones", "David Lebón", "Obús", "Gabriel Rocca", "Nito Mestre", "Charly García", "Norberto 'Pappo' Napolitano", "La Torre", "Los Twist", "Barrio", "Oveja Negra", "Autobus", "Teléfono Rojo", "Hangar", "Abrelatas", "Melody Maker", "Record Mirror"]

colaboradores= ["Daniel Osvaldo Ripoll", "Juan Manuel Cibeira", "Osvaldo Marzullo", "Daniel Lauría", "Oscar Botto", "Walter Martínez", "Marta Ferro", "José Ángel Wolfman"]

discos = []

poster1 = "Robert Plant"
+++

**Póster**: Robert Plant.

**Nota de tapa**: El Libro del Año 1983.

**Reportajes**: Danny Peyronel de Riff. Men At Work. David Gilmour de Pink Floyd. The Animals. Steavie Ray Vaughan.

**Entrevistas**: Leonor Marchesi de Púrpura.

**Notas sobre**:

- Balance Provisional. Lo que pasó en el Rock Nacional '83.

- La prensa musical (1).

- Los que vinieron. Van Halen, Barón Rojo, Rubén Blades.

- El regreso del año: David Bowie.

- Después de la fiebre de sábado... Ahora el cine danza. Flashdance. Manteniéndose vivo.

- El supergrupo del año. Salvado por el rock. Concierto en beneficio de Ronnie Lane.

- El contrato del año. Más oro para los Stones.

- Los músicos argentinos eligen El Disco del Año.

- Los que se vienen.

- Lo que se dijo.

- Lo que el año nos dejó.

**Secciones**:

- Movimientos. Cartelera. Avisos Libres. Paren Las Máquinas.


text:
package io.yawp.servlet.rest;

import io.yawp.repository.query.QueryBuilder;
import io.yawp.repository.query.QueryOptions;

import java.util.List;

public class IndexRestAction extends RestAction {

	public IndexRestAction() {
		super("index");
	}

	@Override
	public void shield() {
		shield.protectIndex();
	}

	@Override
	public List<?> action() {
		QueryBuilder<?> query = query();

		if (id != null) {
			query.from(id);
		}

		if (params.containsKey(QUERY_OPTIONS)) {
			query.options(QueryOptions.parse(params.get(QUERY_OPTIONS)));
		}

		if (hasTransformer()) {
			return query.transform(getTransformerName()).list();
		}

		if (hasShieldCondition()) {
			query.and(shield.getCondition());
		}

		List<?> objects = query.list();
		applyGetFacade(objects);
		return objects;
	}

}

redpajama_set_name: RedPajamaGithub


text:
import copy

from django.test import SimpleTestCase

from unittest.mock import patch

from corehq.apps.app_manager.exceptions import ScheduleError
from corehq.apps.app_manager.models import (
    Application,
    DetailColumn,
    FormActionCondition,
    FormSchedule,
    SchedulePhase,
    SchedulePhaseForm,
    ScheduleVisit,
)
from corehq.apps.app_manager.tests.util import TestXmlMixin, patch_get_xform_resource_overrides

class ScheduleTest(SimpleTestCase, TestXmlMixin):
    file_path = ('data', 'suite')

    def setUp(self):
        self.is_usercase_in_use_patch = patch('corehq.apps.app_manager.models.is_usercase_in_use')
        self.is_usercase_in_use_mock = self.is_usercase_in_use_patch.start()
        self.is_usercase_in_use_mock.return_value = True
        self.app = Application.wrap(self.get_json('suite-advanced'))

        self.module = self.app.get_module(1)
        self.module.has_schedule = True
        self.form_1 = self.module.get_form(0)
        self.form_2 = self.module.get_form(1)
        self.form_3 = self.module.get_form(2)

        self._add_form_abbreviations()
        self._add_form_schedules()
        self._add_form_detail_variable()

    def _add_form_abbreviations(self):
        self.form_1.schedule_form_id = "हिन्दी"
        self.form_2.schedule_form_id = "a983e9"
        self.form_3.schedule_form_id = "39f0ea"

    def _add_form_schedules(self):
        self.form_1.schedule = FormSchedule(
            expires=120,
            starts=-5,
            visits=[
                ScheduleVisit(due=5, expires=4, starts=-5),
                ScheduleVisit(due=10, expires=9),
                ScheduleVisit(starts=5, expires=100, repeats=True, increment=15)
            ]
        )

        self.form_2.schedule = FormSchedule(
            allow_unscheduled=True,
            visits=[
                ScheduleVisit(due=7, expires=4),
                ScheduleVisit(due=15)
            ]
        )

        self.form_3.schedule = FormSchedule(
            visits=[
                ScheduleVisit(due=9, expires=1),
                ScheduleVisit(due=11)
            ]
        )

    def _add_form_detail_variable(self):
        self.module.case_details.short.columns.append(
            DetailColumn(
                header={'en': 'Next due'},
                model='case',
                field='schedule:nextdue',
                format='plain',
            )
        )

    def tearDown(self):
        self.is_usercase_in_use_patch.stop()

    def _apply_schedule_phases(self):
        self.module.schedule_phases = [
            SchedulePhase(  # phase 1
                anchor='edd',
                forms=[SchedulePhaseForm(form_id=self.form_1.unique_id),
                       SchedulePhaseForm(form_id=self.form_2.unique_id)],
            ),
            SchedulePhase(  # phase 2
                anchor='dob',
                forms=[SchedulePhaseForm(form_id=self.form_3.unique_id)]
            ),
        ]

    def test_get_phase(self):
        phase = SchedulePhase(
            anchor='some_case_property',
            forms=[SchedulePhaseForm(form_id=self.form_1.unique_id),
                   SchedulePhaseForm(form_id=self.form_2.unique_id)],
        )

        self.module.schedule_phases = [phase]

        self.assertEqual(self.form_1.get_phase(), phase)
        self.assertEqual(self.form_3.get_phase(), None)

    @patch_get_xform_resource_overrides()
    def test_phase_requires_anchor(self, *args):
        self.module.schedule_phases = [
            SchedulePhase(
                forms=[SchedulePhaseForm(form_id=self.form_3.unique_id)]
            ),
        ]
        with self.assertRaises(ScheduleError):
            self.app.create_suite()

    def test_get_or_create_schedule_phase(self):
        pre_made_phase = SchedulePhase(anchor='sea-floor')
        self.module.schedule_phases = [pre_made_phase]

        phase, created = self.module.get_or_create_schedule_phase(anchor='hook')
        self.assertTrue(created)

        phase_2, created = self.module.get_or_create_schedule_phase(anchor='sea-floor')
        self.assertFalse(created)
        self.assertEqual(phase_2, pre_made_phase)

        with self.assertRaises(ScheduleError):
            self.module.get_or_create_schedule_phase(anchor='  \n\n\n\t\t')

        with self.assertRaises(ScheduleError):
            self.module.get_or_create_schedule_phase(anchor=None)

    def test_update_schedule_phases(self):
        pre_made_phase = SchedulePhase(anchor='foo')
        pre_made_phase_2 = SchedulePhase(anchor='bar')
        self.module.schedule_phases = [pre_made_phase, pre_made_phase_2]

        new_phase = SchedulePhase(anchor='baz')
        updated_phases = [new_phase.anchor, pre_made_phase.anchor]

        self.module.update_schedule_phases(updated_phases)
        self.assertEqual([phase.anchor for phase in self.module.get_schedule_phases()], updated_phases)

        # Test reordering
        self.module.schedule_phases = [pre_made_phase, pre_made_phase_2]
        updated_phases = [pre_made_phase_2.anchor, pre_made_phase.anchor]
        self.module.update_schedule_phases(updated_phases)
        self.assertEqual([phase.anchor for phase in self.module.get_schedule_phases()], updated_phases)

        # Test deletion
        self.module.schedule_phases = [pre_made_phase, pre_made_phase_2]
        updated_phases = []
        self.module.update_schedule_phases(updated_phases)
        self.assertEqual([phase.anchor for phase in self.module.get_schedule_phases()], updated_phases)

        # Test deletion with forms
        phase_with_forms = SchedulePhase(
            anchor='edd',
            forms=[SchedulePhaseForm(form_id=self.form_1.unique_id)],
        )
        self.module.schedule_phases = [phase_with_forms]
        updated_phases = []
        with self.assertRaises(ScheduleError):
            self.module.update_schedule_phases(updated_phases)

    def test_update_schedule_phase_anchors(self):
        pre_made_phase = SchedulePhase(anchor='foo',
                                       forms=[SchedulePhaseForm(form_id=self.form_1.unique_id)],)
        pre_made_phase_2 = SchedulePhase(anchor='bar',
                                         forms=[SchedulePhaseForm(form_id=self.form_2.unique_id)])
        pre_made_phase_3 = SchedulePhase(anchor='burp')
        self.module.schedule_phases = [pre_made_phase, pre_made_phase_2, pre_made_phase_3]

        new_anchors = [(2, 'baz'), (1, 'quux')]

        self.module.update_schedule_phase_anchors(new_anchors)
        self.assertEqual(self.module.schedule_phases[0].forms[0].form_id, self.form_1.unique_id)
        self.assertEqual(self.module.schedule_phases[0].anchor, new_anchors[1][1])

        self.assertEqual(self.module.schedule_phases[1].forms[0].form_id, self.form_2.unique_id)
        self.assertEqual(self.module.schedule_phases[1].anchor, new_anchors[0][1])

        self.assertEqual(self.module.schedule_phases[2].anchor, 'burp')

    @patch_get_xform_resource_overrides()
    def test_form_in_phase_requires_schedule(self, *args):
        self._apply_schedule_phases()
        self.form_3.schedule = None
        with self.assertRaises(ScheduleError):
            self.app.create_suite()

        self.module.schedule_phases.pop()
        self.app.create_suite()

    def test_remove_form_from_phase(self):
        form_1 = self.form_1
        form_2 = self.form_2
        self.module.schedule_phases = [
            SchedulePhase(
                anchor='dob',
                forms=[SchedulePhaseForm(form_id=form_1.unique_id),
                       SchedulePhaseForm(form_id=form_2.unique_id)]
            )
        ]
        phase = next(self.module.get_schedule_phases())  # get the phase through the module so we have a _parent
        phase.remove_form(form_1)

        self.assertEqual(len(phase.forms), 1)
        self.assertEqual([form_2], list(phase.get_forms()))

        with self.assertRaises(ScheduleError):
            phase.remove_form(form_1)

    def test_add_form_to_phase(self):
        self.module.schedule_phases = [
            SchedulePhase(
                anchor='dob',
                forms=[SchedulePhaseForm(form_id=self.form_1.unique_id),
                       SchedulePhaseForm(form_id=self.form_2.unique_id)]
            ),
            SchedulePhase(anchor='second_phase', forms=[]),
        ]
        phases = list(self.module.get_schedule_phases())
        phase1 = phases[0]
        phase1.add_form(self.form_3)
        self.assertEqual(phase1.get_phase_form_index(self.form_3), 2)

        # adding a form to a different phase removes it from the first phase
        phase2 = phases[1]
        phase2.add_form(self.form_3)
        self.assertEqual(phase2.get_phase_form_index(self.form_3), 0)
        self.assertIsNone(phase1.get_form(self.form_3))

    @patch_get_xform_resource_overrides()
    def test_schedule_detail(self, *args):
        self._apply_schedule_phases()

        suite = self.app.create_suite()
        self.assertXmlPartialEqual(self.get_xml('schedule-entry'), suite, "./detail[@id='m1_case_short']")

    @patch_get_xform_resource_overrides()
    def test_schedule_fixture(self, *args):
        self._apply_schedule_phases()

        suite = self.app.create_suite()
        self.assertXmlPartialEqual(self.get_xml('schedule-fixture'), suite, './fixture')

    @patch('corehq.apps.app_manager.suite_xml.post_process.resources.ResourceOverrideHelper.update_suite')
    @patch_get_xform_resource_overrides()
    def test_multiple_modules(self, *args):
        self._apply_schedule_phases()

        other_module = self.app.get_module(2)
        other_module.has_schedule = True
        scheduled_form = other_module.get_form(0)
        scheduled_form.schedule = FormSchedule(
            visits=[
                ScheduleVisit(due=9),
                ScheduleVisit(due=11)
            ]
        )
        other_module.forms.append(copy.copy(scheduled_form))

        other_module.schedule_phases = [
            SchedulePhase(
                anchor='case_property',
                forms=[SchedulePhaseForm(form_id=scheduled_form.unique_id)]
            )
        ]

        expected_fixture = """
             <partial>
             <fixture id="schedule:m2:p1:f0">
                 <schedule expires="" allow_unscheduled="False">
                     <visit id="1" due="9" repeats="False"/>
                     <visit id="2" due="11" repeats="False"/>
                 </schedule>
             </fixture>
             </partial>
        """

        suite = self.app.create_suite()

        self.assertXmlPartialEqual(expected_fixture, suite, './fixture[@id="schedule:m2:p1:f0"]')
        self.assertXmlHasXpath(suite, './fixture[@id="schedule:m1:p1:f0"]')

    @patch_get_xform_resource_overrides()
    def test_form_filtering(self, *args):
        self._apply_schedule_phases()
        suite = self.app.create_suite()
        form_ids = (self.form_1.schedule_form_id, self.form_2.schedule_form_id)
        case_load_actions = ["case_id_case_clinic", "case_id_load_clinic0"]
        case = ["instance('casedb')/casedb/case[@case_id=instance('commcaresession')/session/data/{}]"
                .format(action) for action in case_load_actions]
        for form_num, form_id in enumerate(form_ids):
            anchor = "{case}/edd".format(case=case[form_num])
            current_schedule_phase = "{case}/current_schedule_phase".format(case=case[form_num])
            visit = "instance('schedule:m1:p1:f{form_num}')/schedule/visit".format(form_num=form_num)
            schedule = "instance('schedule:m1:p1:f{form_num}')/schedule".format(form_num=form_num)

            current_phase_query = (
                "({current_schedule_phase} = '' or {current_schedule_phase} = 1)"
            ).format(current_schedule_phase=current_schedule_phase)

            within_form_relevancy = (
                "today() >= (date({anchor}) + int({schedule}/@starts)) and "
                "({schedule}/@expires = '' or today() <= (date({anchor}) + int({schedule}/@expires)))"
            ).format(schedule=schedule, anchor=anchor)

            next_valid_schedules = (
                "{current_phase_query} and "
                "{anchor} != '' and "
                "({within_form_relevancy})"
            ).format(current_phase_query=current_phase_query, anchor=anchor,
                     within_form_relevancy=within_form_relevancy)

            allow_unscheduled = (
                "{schedule}/@allow_unscheduled = 'True'"
            ).format(schedule=schedule)

            upcoming_scheduled_visits = (
                "{visit}"
                "[{case}/last_visit_number_{form_id} = '' or "
                    "if(@repeats = 'True', @id >= {case}/last_visit_number_{form_id},"
                        " @id > {case}/last_visit_number_{form_id})]"
                "[if(@repeats = 'True', "
                    "today() >= (date({case}/last_visit_date_{form_id}) + int(@increment) + int(@starts)) and "  # noqa
                        "(@expires = '' or today() <= (date({case}/last_visit_date_{form_id}) + int(@increment)"  # noqa
                        " + int(@expires))), "
                    "today() >= (date({anchor}) + int(@due) + int(@starts)) and "
                        "(@expires = '' or today() <= (date({anchor}) + int(@due) + int(@expires)))"
                ")]"
            ).format(visit=visit, case=case[form_num], form_id=form_id, anchor=anchor)

            visit_allowed = (
                "{allow_unscheduled} or "
                "count({upcoming_scheduled_visits}) > 0"
            ).format(allow_unscheduled=allow_unscheduled, upcoming_scheduled_visits=upcoming_scheduled_visits)

            filter_condition = (
                "({next_valid_schedules}) and ({visit_allowed})"
            ).format(next_valid_schedules=next_valid_schedules, visit_allowed=visit_allowed)

            partial = """
            <partial>
                <command id='m1-f{form_num}' relevant="{filter_condition}" />
            </partial>
            """.format(form_num=form_num, filter_condition=filter_condition)

            self.assertXmlPartialEqual(partial, suite, './menu/command[@id="m1-f{}"]'.format(form_num))

    # xmlns is added because I needed to use WrappedNode.find() in the next few tests
    xmlns = ("xmlns='http://www.w3.org/2002/xforms' "
             "xmlns:h='http://www.w3.org/1999/xhtml' "
             "xmlns:jr='http://openrosa.org/javarosa' "
             "xmlns:orx='http://openrosa.org/jr/xforms' "
             "xmlns:xsd='http://www.w3.org/2001/XMLSchema'")

    def test_current_schedule_phase(self):
        """ Current Schedule Phase is set depending on transition and termination conditions """
        current_schedule_phase_partial = """
        <partial>
            <bind type="xs:integer"
                  nodeset="/data/case_case_clinic/case/update/current_schedule_phase"
                  calculate="{value}"
            {xmlns}/>
        </partial>
        """
        transition_question = '/data/successful_birth'
        transition_answer = 'yes'
        self.form_1.schedule.transition_condition = FormActionCondition(
            type='if',
            question=transition_question,
            answer=transition_answer,
        )

        termination_question = '/data/passed_away'
        termination_answer = 'yes'
        self.form_1.schedule.termination_condition = FormActionCondition(
            type='if',
            question=termination_question,
            answer=termination_answer,
        )

        self._apply_schedule_phases()

        xform_1 = self.form_1.wrapped_xform()
        self.form_1.add_stuff_to_xform(xform_1)
        value = "if({termination_condition}, -1, if({transition_condition}, 2, 1))".format(
            termination_condition="{} = '{}'".format(termination_question, termination_answer),
            transition_condition="{} = '{}'".format(transition_question, transition_answer),
        )
        self.assertXmlPartialEqual(
            current_schedule_phase_partial.format(value=value, xmlns=self.xmlns),
            (xform_1.model_node.find(
                './bind[@nodeset="/data/case_case_clinic/case/update/current_schedule_phase"]')
             .render()),
            '.'
        )

    def test_current_schedule_phase_no_transitions(self):
        """The current_schedule_phase is set to the phase of the current form"""
        self._apply_schedule_phases()

        current_schedule_phase_partial = """
        <partial>
            <bind type="xs:integer"
                  nodeset="/data/case_load_clinic0/case/update/current_schedule_phase"
                  calculate="{value}"
            {xmlns}/>
        </partial>
        """
        value = "if(false(), -1, if(false(), 2, {}))".format(self.form_2.get_phase().id)
        xform_2 = self.form_2.wrapped_xform()
        self.form_2.add_stuff_to_xform(xform_2)
        self.assertXmlPartialEqual(
            current_schedule_phase_partial.format(value=value, xmlns=self.xmlns),
            (xform_2.model_node.find(
                './bind[@nodeset="/data/case_load_clinic0/case/update/current_schedule_phase"]')
             .render()),
            '.'
        )

    def test_last_visit_number(self):
        """ Increment the visit number for that particular form. If it is empty, set it to 1 """
        last_visit_number_partial = """
        <partial>
            <bind nodeset="/data/case_case_clinic/case/update/last_visit_number_{form_id}"
                  calculate="/data/current_visit_number"
                  relevant="not(/data/unscheduled_visit)"
            {xmlns}/>
        </partial>
        """
        self._apply_schedule_phases()
        xform_1 = self.form_1.wrapped_xform()
        form_id = self.form_1.schedule_form_id
        self.form_1.add_stuff_to_xform(xform_1)
        self.assertXmlPartialEqual(
            last_visit_number_partial.format(form_id=form_id, xmlns=self.xmlns),
            (xform_1.model_node.find('./bind[@nodeset="/data/case_case_clinic/case/update/last_visit_number_{}"]'
                                     .format(form_id)).render()),
            '.'
        )

    def test_last_visit_date(self):
        """ Set the date of the last visit when a form gets submitted """
        last_visit_date_partial = """
        <partial>
            <bind nodeset="/data/case_case_clinic/case/update/last_visit_date_{form_id}"
                  type="xsd:dateTime"
                  calculate="/data/meta/timeEnd"
                  relevant="not(/data/unscheduled_visit)"
            {xmlns}/>
        </partial>
        """
        self._apply_schedule_phases()
        xform_1 = self.form_1.wrapped_xform()
        form_id = self.form_1.schedule_form_id
        self.form_1.add_stuff_to_xform(xform_1)
        self.assertXmlPartialEqual(
            last_visit_date_partial.format(form_id=form_id, xmlns=self.xmlns),
            (xform_1.model_node.find('./bind[@nodeset="/data/case_case_clinic/case/update/last_visit_date_{}"]'
                                     .format(form_id)).render()),
            '.'
        )

    def test_next_visit_date(self):
        """ add next_visit_date to each form """
        next_visit_date_partial = """
        <partial>
            <bind nodeset="/data/next_visit_date"
                  calculate="date(min({form_names}))"
            {xmlns}/>
        </partial>
        """
        self._apply_schedule_phases()
        phase_forms = [self.form_1, self.form_2]
        xform_1 = self.form_1.wrapped_xform()
        self.form_1.add_stuff_to_xform(xform_1)
        form_names = ["/data/next_{}".format(f.schedule_form_id) for f in phase_forms]

        self.assertXmlPartialEqual(
            next_visit_date_partial.format(form_names=",".join(form_names), xmlns=self.xmlns),
            xform_1.model_node.find('./bind[@nodeset="/data/next_visit_date"]').render(),
            '.'
        )

        for form in phase_forms:
            self.assertTrue(
                len(xform_1.model_node.find("./bind[@nodeset='/data/next_{}']"
                                            .format(form.schedule_form_id)).render())
                > 0)


text:
package com.pmease.commons.xmt.bean;

import java.util.List;
import java.util.Stack;

import com.pmease.commons.xmt.VersionedDocument;

public class CompileTask extends AbstractCompileTask {

    public List<String> srcFiles;
    public String destDir = "classes";

    @SuppressWarnings("unused")
    private void migrate1(VersionedDocument dom, Stack<Integer> versions) {
        dom.getRootElement().addElement("destDir").setText("classes");
    }

    @SuppressWarnings("unused")
    private void migrate2(VersionedDocument dom, Stack<Integer> versions) {
        versions.push(0);
        dom.getRootElement().addElement("options").setText("-debug");
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Consp. System. Corticiac. (Tartu) 215 (1968)

#### Original name
Hyphodontia pilaecystidiata f. crassa Parmasto

### Remarks
null


text:
package ru.job4j.map;

import org.junit.Test;

import static org.junit.Assert.assertTrue;

/**
 * Created by Ivan Sliusar on 11.10.2017.
 * Red Line Soft corp.
 */
public class HandBookTest {
    /**
     * Test insert.
     */
    @Test
    public void whenInsertExistingValueThenFalse() {
        HandBook<Integer, String> handBook = new HandBook<>();
        handBook.insert(1, "Petrov");
        handBook.insert(2, "Ivanov");

        assertTrue(!handBook.insert(1, "Sidorov"));
    }

    /**
     * Test delete.
     */
    @Test
    public void whenDeleteExistingValueThenTrue() {
        HandBook<Integer, String> handBook = new HandBook<>();
        handBook.insert(300, "Petrov");
        handBook.insert(-200, "Ivanov");

        boolean result = handBook.delete(300);
        assertTrue(result);
    }

    /**
     * Test get.
     */
    @Test
    public void whenGetbyKeyExistingValueThenReturnValue() {
        HandBook<Integer, String> handBook = new HandBook<>();
        handBook.insert(1, "Petrov");
        handBook.insert(2, "Ivanov");

        String result = handBook.get(1);
        assertTrue("Petrov".equals(result));
    }

}


text:
from __future__ import unicode_literals

import struct
import time

from c1219.constants import *

def format_ltime(endianess, tm_format, data):
	"""
	Return data formatted into a human readable time stamp.

	:param str endianess: The endianess to use when packing values ('>' or '<')
	:param int tm_format: The format that the data is packed in, this typically
	  corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
	:param bytes data: The packed and machine-formatted data to parse
	:rtype: str
	"""
	if tm_format == 0:
		return ''
	elif tm_format == 1 or tm_format == 2:  # I can't find solid documentation on the BCD data-type
		y = data[0]
		year = '????'
		if 90 <= y <= 99:
			year = '19' + str(y)
		elif 0 <= y <= 9:
			year = '200' + str(y)
		elif 10 <= y <= 89:
			year = '20' + str(y)
		month = data[1]
		day = data[2]
		hour = data[3]
		minute = data[4]
		second = data[5]
	elif tm_format == 3 or tm_format == 4:
		if tm_format == 3:
			u_time = float(struct.unpack(endianess + 'I', data[0:4])[0])
			second = float(data[4])
			final_time = time.gmtime((u_time * 60) + second)
		elif tm_format == 4:
			final_time = time.gmtime(float(struct.unpack(endianess + 'I', data[0:4])[0]))
		year = str(final_time.tm_year)
		month = str(final_time.tm_mon)
		day = str(final_time.tm_mday)
		hour = str(final_time.tm_hour)
		minute = str(final_time.tm_min)
		second = str(final_time.tm_sec)

	return "{0} {1} {2} {3}:{4}:{5}".format((MONTHS.get(month) or 'UNKNOWN'), day, year, hour, minute, second)

def get_history_entry_record(endianess, hist_date_time_flag, tm_format, event_number_flag, hist_seq_nbr_flag, data):
	"""
	Return data formatted into a log entry.

	:param str endianess: The endianess to use when packing values ('>' or '<')
	:param bool hist_date_time_flag: Whether or not a time stamp is included.
	:param int tm_format: The format that the data is packed in, this typically
	  corresponds with the value in the GEN_CONFIG_TBL (table #0) (1 <= tm_format <= 4)
	:param bool event_number_flag: Whether or not an event number is included.
	:param bool hist_seq_nbr_flag: Whether or not an history sequence number
	  is included.
	:param str data: The packed and machine-formatted data to parse
	:rtype: dict
	"""
	rcd = {}
	if hist_date_time_flag:
		tmstmp = format_ltime(endianess, tm_format, data[0:LTIME_LENGTH.get(tm_format)])
		if tmstmp:
			rcd['Time'] = tmstmp
		data = data[LTIME_LENGTH.get(tm_format):]
	if event_number_flag:
		rcd['Event Number'] = struct.unpack(endianess + 'H', data[:2])[0]
		data = data[2:]
	if hist_seq_nbr_flag:
		rcd['History Sequence Number'] = struct.unpack(endianess + 'H', data[:2])[0]
		data = data[2:]
	rcd['User ID'] = struct.unpack(endianess + 'H', data[:2])[0]
	rcd['Procedure Number'], rcd['Std vs Mfg'] = get_table_idbb_field(endianess, data[2:4])[:2]
	rcd['Arguments'] = data[4:]
	return rcd

def get_table_idbb_field(endianess, data):
	"""
	Return data from a packed TABLE_IDB_BFLD bit-field.

	:param str endianess: The endianess to use when packing values ('>' or '<')
	:param str data: The packed and machine-formatted data to parse
	:rtype: tuple
	:return: Tuple of (proc_nbr, std_vs_mfg)
	"""
	bfld = struct.unpack(endianess + 'H', data[:2])[0]
	proc_nbr = bfld & 0x7ff
	std_vs_mfg = bool(bfld & 0x800)
	selector = (bfld & 0xf000) >> 12
	return (proc_nbr, std_vs_mfg, selector)

def get_table_idcb_field(endianess, data):
	"""
	Return data from a packed TABLE_IDC_BFLD bit-field.

	:param str endianess: The endianess to use when packing values ('>' or '<')
	:param str data: The packed and machine-formatted data to parse
	:rtype: tuple
	:return: Tuple of (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3)
	"""
	bfld = struct.unpack(endianess + 'H', data[:2])[0]
	proc_nbr = bfld & 2047
	std_vs_mfg = bool(bfld & 2048)
	proc_flag = bool(bfld & 4096)
	flag1 = bool(bfld & 8192)
	flag2 = bool(bfld & 16384)
	flag3 = bool(bfld & 32768)
	return (proc_nbr, std_vs_mfg, proc_flag, flag1, flag2, flag3)

class C1219ProcedureInit(object):
	"""
	A C1219 Procedure Request, this data is written to table 7 in order to
	start a procedure.

	:param str endianess: The endianess to use when packing values ('>' or '<')
	:param int table_proc_nbr: The numeric procedure identifier (0 <= table_proc_nbr <= 2047).
	:param bool std_vs_mfg: Whether the procedure is manufacturer specified
	  or not.  True is manufacturer specified.
	:param int selector: Controls how data is returned (0 <= selector <= 15).
	  0: Post response in PROC_RESPONSE_TBL (#8) on completion.
	  1: Post response in PROC_RESPONSE_TBL (#8) on exception.
	  2: Do not post response in PROC_RESPONSE_TBL (#8).
	  3: Post response in PROC_RESPONSE_TBL (#8) immediately and another response in PROC_RESPONSE_TBL (#8) on completion.
	  4-15: Reserved.
	:param int seqnum: The identifier for this procedure to be used for
	  coordination (0x00 <= seqnum <= 0xff).
	:param str params: The parameters to pass to the procedure initiation
	  request.
	"""
	def __init__(self, endianess, table_proc_nbr, std_vs_mfg, selector, seqnum, params=b''):
		mfg_defined = 0
		if std_vs_mfg:
			mfg_defined = 1
		self.mfg_defined = bool(mfg_defined)
		self.selector = selector

		mfg_defined <<= 11
		selector <<= 12

		self.table_idb_bfld = struct.pack(endianess + 'H', (table_proc_nbr | mfg_defined | selector))
		self.endianess = endianess
		self.proc_nbr = table_proc_nbr
		self.seqnum = seqnum
		self.params = params

	def __repr__(self):
		return "<{0} mfg_defined={1} proc_nbr={2} >".format(self.__class__.__name__, self.mfg_defined, self.proc_nbr)

	def __str__(self):
		return self.build()

	def build(self):
		return self.table_idb_bfld + struct.pack('B', self.seqnum) + self.params

	@classmethod
	def from_bytes(cls, endianess, data):
		if len(data) < 3:
			raise Exception('invalid data (size)')
		proc_nbr, std_vs_mfg, selector = get_table_idbb_field(endianess, data[0:2])
		seqnum = data[2]
		return cls(endianess, proc_nbr, std_vs_mfg, selector, seqnum, data[3:])


text:
package com.sean.im.friend.action;

import com.sean.config.core.Config;
import com.sean.im.friend.constant.Params;
import com.sean.im.friend.constant.RetParams;
import com.sean.service.annotation.ActionConfig;
import com.sean.service.core.Action;
import com.sean.service.core.Session;

@ActionConfig(description = "管理员登录", authenticate = false,
mustParams = { Params.username, Params.password },
returnParams = { RetParams.loginrs })
public class AdminLoginAction extends Action
{
	@Override
	public void execute(Session session) throws Exception
	{
		String username = session.getParameter(Params.username);
		String password = session.getParameter(Params.password);

		String _username = Config.getProperty("console.username");
		String _password = Config.getProperty("console.password");

		if (username.equals(_username) && password.equals(_password))
		{
			session.setReturnAttribute(RetParams.loginrs, 1);
			session.success();
		}
		else
		{
			session.setReturnAttribute(RetParams.loginrs, 0);
			session.success();
		}
	}
}


text:
/**
 *
 */
package org.sakaiproject.search.jdbc;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

public class WrappingDataSource implements DataSource {

	private DataSource wds;

	public WrappingDataSource(DataSource ds)
	{
		wds = ds;
	}

	public Connection getConnection() throws SQLException
	{
		return wds.getConnection();
	}

	public Connection getConnection(String username, String password)
			throws SQLException
	{
		return wds.getConnection(username, password);
	}

	public PrintWriter getLogWriter() throws SQLException
	{
		return wds.getLogWriter();
	}

	public int getLoginTimeout() throws SQLException
	{
		return wds.getLoginTimeout();
	}

	public void setLogWriter(PrintWriter out) throws SQLException
	{
		wds.setLogWriter(out);
	}

	public void setLoginTimeout(int seconds) throws SQLException
	{
		wds.setLoginTimeout(seconds);
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return isWrapperFor(iface);
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return unwrap(iface);
	}
}


text:
import re
from ..exceptions import ShowerConfigException
from .data import Data

class DataRegex(Data):
    def __init__(self, conf):
        self.command = None
        self.regex = None
        super(DataRegex, self).__init__(conf)

    def _from_conf(self, conf):
        super(DataRegex, self)._from_conf(conf)
        for node in conf.children:
            key = node.key.lower()
            if key == 'command':
                setattr(self, key, str(node.values[0]))
            elif key == 'regex':
                setattr(self, key, re.compile(node.values[0]))

    def _validate(self):
        super(DataRegex, self)._validate()
        if not self.command:
            raise ShowerConfigException('Missing Command in Data "{}" section'.format(self.name))
        if not self.regex:
            raise ShowerConfigException('Missing Regex in Data "{}" section'.format(self.name))

    def parse(self, output):
        results = {}
        if self.table:
            parsed = self._parse_by_line(output)
            for row in parsed:
                self._add_to_results(results, row['_'.join(self.typeinstance)], row)
        else:
            parsed = self._parse_line(output)
            self._add_to_results(results, '0', parsed)
        return results

    def _add_to_results(self, results, instance, matches):
        if not matches:
            return
        fields = {typ: float(matches[typ]) for typ in self.types}
        results[instance] = fields

    def _parse_by_line(self, output):
        parsed = []
        for line in output.split('\n'):
            parsed.append(self._parse_line(line))
        return parsed

    def _parse_line(self, line):
        m = self.regex.search(line)
        self.log('info', repr(self.regex.pattern))
        self.log('info', repr(line))
        if m:
            self.log('info', repr(m.groupdict()))
            return m.groupdict()
        else:
            self.log('info', repr(None))
            return None


text:
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("logRegBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

// .............Registration form JS

$(document).ready(function() {
    $('#contact_form').bootstrapValidator({

        // To use feedback icons, ensure that you use Bootstrap v3.1.0 or later

        feedbackIcons: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },

        fields: {
            first_name: {
                validators: {
                        stringLength: {
                        min: 2,
                    },
                        notEmpty: {
                        message: 'Please enter your First Name'
                    }
                }
            },

             last_name: {
                validators: {
                     stringLength: {
                        min: 2,
                    },
                    notEmpty: {
                        message: 'Please enter your Last Name'
                    }
                }
            },
			 user_name: {
                validators: {
                     stringLength: {
                        min: 8,
                    },
                    notEmpty: {
                        message: 'Please enter your Username'
                    }
                }
            },
			 user_password: {
                validators: {
                     stringLength: {
                        min: 8,
                    },
                    notEmpty: {
                        message: 'Please enter your Password'
                    }
                }
            },

			confirm_password: {
                validators: {
                     stringLength: {
                        min: 8,
                    },
                    notEmpty: {
                        message: 'Please confirm your Password'
                    }
                }
            },

            email: {
                validators: {
                    notEmpty: {
                        message: 'Please enter your Email Address'
                    },
                    emailAddress: {
                        message: 'Please enter a valid Email Address'
                    }
                }
            },

            contact_no: {
                validators: {
                  stringLength: {
                        min: 12,
                        max: 12
                    },
                    notEmpty: {
                        message: 'Please enter your Contact No.'
                     }
            	}

                }
            }
        })

        .on('success.form.bv', function(e) {
            $('#success_message').slideDown({ opacity: "show" }, "slow"); // Do something ...
                $('#contact_form').data('bootstrapValidator').resetForm();

            // Prevent form submission
            e.preventDefault();

            // Get the form instance
            var $form = $(e.target);

            // Get the BootstrapValidator instance
            var bv = $form.data('bootstrapValidator');

            // Use Ajax to submit form data
            $.post($form.attr('action'), $form.serialize(), function(result) {
                console.log(result);
            }, 'json');
        });
});


text:
/*
 * Problem 97: Large non-Mersenne prime
 *
 * https://projecteuler.net/problem=97
 */

#include <stdio.h>

#define MAX 10000000000
#define EXPONENT 7830457

int main(){
	//The largest 10 digit number is 34 bit long, so we need a longer datatype than an int
	unsigned long long result = 1;
	int i;
	//Perform the 2^EXPONENT operation
	for (i = 0; i < EXPONENT; i++){
		result *= 2;
		//Truncate the result to 10 digits as soon as it becomes 11 digits long, this
		//	overcomes the precision issue
		if (result >= MAX){
			result %= MAX;
		}
	}

	//Perform the remainder of the operation and truncate again
	result = (result*28433 + 1)%MAX;

	printf("The last ten digits of 28433*2^7830457+1 are %llu\n", result);
	return 0;
}


text:
using UnityEngine;
using System.Collections;

public class testDamages : MonoBehaviour {

    AvatarHealthManager ahm;

	// Use this for initialization
	void Start ()
    {
        ahm = FindObjectOfType<AvatarHealthManager>();
	}

	// Update is called once per frame
	void Update ()
    {
	    if (Input.GetKeyDown(KeyCode.U))
        {
            ahm.Armor += 10;
        }

        if (Input.GetKeyDown(KeyCode.I))
        {
            ahm.Life += 10;
        }

        if (Input.GetKeyDown(KeyCode.O))
        {
            ahm.TakeDamages(10);
        }
    }
}


text:
layout: figure
order: 2
label: Figure 2
title: "Perception of Corruption in the country"
description: "Click on the graph to open the enlarged interactive view"
image: "data/corr_nat_eb2014-thumb.png"
---
Press escape to exit
<iframe src="{{ site.baseurl }}/data/t.html" width="800" height="800" allowfullscreen></iframe>


text:
using Microsoft.Xna.Framework.Graphics;

namespace NgxLib
{
    public class WorldRenderLayer : NgxRenderLayer
    {
        public override void Begin(SpriteBatch batch)
        {
            batch.Begin(
                SpriteSortMode.Immediate,
                BlendState.AlphaBlend,
                SamplerState.PointClamp,
                DepthStencilState.Default,
                RasterizerState.CullCounterClockwise,
                null,
                Context.Camera.Transform);
        }
    }
}


text:
import React from "react";
import "./SpinnerField.scss"
import MDSpinner from "react-md-spinner";

export const SpinnerField = () =>
<MDSpinner/>
;


text:
<!DOCTYPE html>

	<meta charset="utf-8"/>
	<meta name="latexinput" content="mmd-tufte-handout-header"/>
	<title>Glossaries</title>
	<meta name="author" content="Fletcher T. Penney"/>
	<meta name="version" content="4.7.1"/>
	<meta name="revised" content="2014-07-09"/>
	<link type="text/css" rel="stylesheet" href="http://fletcher.github.io/MultiMarkdown-4/css/document.css"/>
	<meta name="latexmode" content="memoir"/>
	<meta name="latexinput" content="mmd-tufte-handout-begin-doc"/>
	<meta name="latexfooter" content="mmd-tufte-footer"/>

Glossaries

MultiMarkdown has a feature that allows footnotes to be specified as glossary
terms. It doesn’t do much for XHTML documents, but the XSLT file that converts
the document into LaTeX is designed to convert these special footnotes into
glossary entries.

The glossary format for the footnotes is:

[^glossaryfootnote]: glossary: term (optional sort key)
    The actual definition belongs on a new line, and can continue on
    just as other footnotes.

The term is the item that belongs in the glossary. The sort key is
optional, and is used to specify that the term should appear somewhere else in
the glossary (which is sorted in alphabetical order).

Unfortunately, it takes an extra step to generate the glossary when creating a
pdf from a latex file:

You need to have the basic.gst file installed, which comes with the
memoir class.

You need to run a special makeindex command to generate the .glo file:
 makeindex -s `kpsewhich basic.gst` -o "filename.gls" "filename.glo"

Then you run the usual pdflatex command again a few times.

Alternatively, you can use the code below to create an engine file for TeXShop
(it belongs in ~/Library/TeXShop/Engines). You can name it something like
MemoirGlossary.engine. Then, when processing a file that needs a glossary,
you typeset your document once with this engine, and then continue to process
it normally with the usual LaTeX engine. Your glossary should be compiled
appropriately. If you use TeXShop, this is the way to go.

Note: Getting glossaries to work is a slightly more advanced LaTeX
feature, and might take some trial and error the first few times.

#!/bin/

set path = ($path /usr/local/teTeX/bin/powerpc-apple-darwin-current
    /usr/local/bin) # This is actually a continuation of the line above

set basefile = `basename "$1" .tex`

makeindex -s `kpsewhich basic.gst` -o "${basefile}.gls" "${basefile}.glo"


text:
require 'spec_helper'

module CampfireExport
  describe Account do
    before(:each) do
      @subdomain = "test-subdomain"
      @api_token = "test-apikey"
      @account   = Account.new(@subdomain, @api_token)

      @good_timezone = '<?xml version="1.0" encoding="UTF-8"?>' +
					   '<account>' +
					   '  <time-zone>America/Los_Angeles</time-zone>' +
					   '  <owner-id type="integer">99999</owner-id>' +
					   '  <created-at type="datetime">2010-01-31T18:30:18Z</created-at>' +
					   '  <storage type="integer">9999999</storage>' +
					   '  <plan>basic</plan>' +
					   '  <updated-at type="datetime">2010-01-31T18:31:55Z</updated-at>' +
					   '  <subdomain>example</subdomain>' +
					   '  <name>Example</name>' +
					   '  <id type="integer">999999</id>' +
					   '</account>'

      @bad_timezone  = @good_timezone.gsub('America/Los_Angeles',
                                           'No Such Timezone')
      @account_xml = double("Account XML")
      @account_xml.stub(:body).and_return(@good_timezone)
    end

    context "when it is created" do
      it "sets up the account config variables" do
        Account.subdomain.should equal(@subdomain)
        Account.api_token.should equal(@api_token)
        Account.base_url.should == "https://#{@subdomain}.campfirenow.com"
      end
    end

    context "when timezone is loaded" do
      it "determines the user's timezone" do
        @account.should_receive(:get).with("/account.xml"
          ).and_return(@account_xml)
        @account.find_timezone
        Account.timezone.to_s.should == "America - Los Angeles"
      end

      it "raises an error if it gets a bad time zone identifier" do
        @account_xml.stub(:body).and_return(@bad_timezone)
        @account.stub(:get).with("/account.xml"
          ).and_return(@account_xml)
        expect {
          @account.find_timezone
        }.to raise_error(TZInfo::InvalidTimezoneIdentifier)
      end

      it "raises an error if it can't get the account settings at all" do
        @account.stub(:get).with("/account.xml"
          ).and_raise(CampfireExport::Exception.new("/account/settings",
            "Not Found", 404))
        expect {
          @account.find_timezone
        }.to raise_error(CampfireExport::Exception)
      end
    end

    context "when rooms are requested" do
      it "returns an array of rooms" do
        room_xml = "<rooms><room>1</room><room>2</room><room>3</room></rooms>"
        room_doc = double("room doc")
        room_doc.should_receive(:body).and_return(room_xml)
        @account.should_receive(:get).with('/rooms.xml').and_return(room_doc)
        room = double("room")
        Room.should_receive(:new).exactly(3).times.and_return(room)
        expect(@account.rooms.size).to eq(3)
      end

      it "raises an error if it can't get the room list" do
        allow(@account).to receive(:get).with('/rooms.xml') { raise(CampfireExport::Exception.new('/rooms.xml', "Not Found", 404)) }

        expect {
          @account.rooms
        }.to raise_error(CampfireExport::Exception)
      end
    end
  end
end


text:
function documentReady() {
    initTableSorter();

    $('.select-all-check-box').live('click', function () {
        $('.indicator-check-box').attr('checked', $(this).is(':checked'));
    });

    toggleInactiveUsers();

    $('#audit_history').click(function () {
        var selectedUsers = [] ;

        $('.indicator-check-box:checked').each(function () {
            selectedUsers.push($(this).val());
        });

        if (selectedUsers.length) {
            loading();

            $.ajax({
                cache: false,
                type: 'Get',
                url: '/user/user-audit',
                data: { jdata: selectedUsers },
                traditional: true,
                dataType: 'html',
                success: function (data) {
                    var h = data;
                    lightbox.show(h, 20, 300, 700);
                    $('#deleteIndicators').show();
                    loadingFinished();
                },
                error: function (xhr, error) {
                    loadingFinished();
                }
            });
        }
    });
}

function toggleInactiveUsers() {
    var inactiveUsersShown = false;

    var $button = $('#toggle-current-users');
    var $inactiveUsers = $('.not-current');

    $('#toggle-current-users').click(function () {

        if (inactiveUsersShown) {
            $button.val('Show inactive users');
            $inactiveUsers.hide();
        } else {
            $button.val('Hide inactive users');
            $inactiveUsers.show();
        }

        inactiveUsersShown = !inactiveUsersShown;
    });
}

$(document).ready(documentReady);


text:
//#define FASTFORMAT_NO_USE_JIT_CACHE

/* STLSoft header files */
#if defined(_WIN32) && \
    defined(_AFXDLL)
# include <mfcstl/mfcstl.hpp>
#endif /* OS */

/* FastFormat header files */
#include <fastformat/internal/stlsoft.h>
#if defined(STLSOFT_COMPILER_IS_MSVC) && \
    _MSC_VER >= 1400
# define _CRT_SECURE_NO_DEPRECATE
# pragma warning(disable : 4996)
# pragma warning(disable : 4505)
#endif
#if defined(STLSOFT_COMPILER_IS_MSVC) && \
    _MSC_VER == 1310
 /* These warnings only for Boost. Ho hum. */
# pragma warning(disable : 4511)
# pragma warning(disable : 4512)
# pragma warning(disable : 4671)
# pragma warning(disable : 4673)
# pragma warning(disable : 4702)
#endif
#if defined(__BORLANDC__) && \
    __BORLANDC__ < 0x0610
 /* Borland is really messed up, so we have to skip around the filter_type
  * mechanism, and instead define string access shims
  *
  * WARNING: The following implementation is hack that is good enough only
  * to make this compilation unit run correctly. Do not take this code and
  * put it into production
  */
# include <stdio.h>
# include <string.h>

    namespace
    {
        char    s_realBuffer[1001];
    }

    namespace stlsoft
    {
        char const* c_str_data_a(double d)
        {
            int n = ::snprintf(&s_realBuffer[0], STLSOFT_NUM_ELEMENTS(s_realBuffer) - 1, "%G", d);

            if(n < 0)
            {
                n = STLSOFT_NUM_ELEMENTS(s_realBuffer) - 1;
            }

            s_realBuffer[n] = '\0';

            return s_realBuffer;
        }
        size_t c_str_len_a(double d)
        {
            return strlen(c_str_data_a(d));
        }
    }

#else /* ? compiler */
# include <fastformat/shims/conversion/filter_type/reals.hpp>
#endif /* compiler */
#include <fastformat/format/specification_defect_handling/ignore_unreferenced_arguments_scope.hpp>

#if defined(_WIN32) && \
    defined(UNIX)
# include <winsock2.h>
# include <sys/time.h>
# include <platformstl/performance/performance_counter.hpp>
#endif

/* STLSoft header files */
#if defined(_WIN32) && \
    defined(_AFXDLL)
# include <mfcstl/mfcstl.hpp>
# include <mfcstl/string/grab_cstring_buffer.hpp>
# include <fastformat/sinks/CString.hpp>
#endif /* OS */
#include <stlsoft/stlsoft.h>
#include <stlsoft/shims/access/string/std/time.hpp>
#include <stlsoft/string/simple_string.hpp>
#include <platformstl/platformstl.h>
#if defined(PLATFORMSTL_OS_IS_WINDOWS)
# include <comstl/shims/access/string.hpp>
#endif /* OS */
#include <platformstl/performance/performance_counter.hpp>

#include <fastformat/sinks/ostream.hpp>
#include <fastformat/fastformat.hpp>

/* Boost header files */
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
# include <boost/format.hpp>
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */

/* Loki header files */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
# include <loki/SafeFormat.h>
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */

/* xTests header files */
#include <xtests/xtests.h>

/* Standard C++ header files */
#include <exception>
#include <iostream>
#include <string>
#include <sstream>

/* Standard C header files */
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#if defined(_MSC_VER) && \
    defined(_DEBUG)
# include <crtdbg.h>
#endif /* _MSC_VER) && _DEBUG */

/* /////////////////////////////////////////////////////////////////////////////
 * Macros
 */

#define TX(x)       FASTFORMAT_LITERAL_STRING(x)

/* /////////////////////////////////////////////////////////////////////////////
 * Globals
 */

extern "C" const char PANTHEIOS_FE_PROCESS_IDENTITY[] = "test.performance.name_age_height";

/* /////////////////////////////////////////////////////////////////////////////
 * Typedefs
 */

struct person_t
{
    char const* name;
    int         age;
    float       height;
};

/* ////////////////////////////////////////////////////////////////////////// */

static int main_(int argc, char** argv)
{
    // 0 - nothing
    // 1 - ratios only, in the form of "t:v; t:v; ..."
    // 2 - ratios only, one-per-line
    // 3 - as is

    int verbosity;

    XTESTS_COMMANDLINE_PARSEVERBOSITY(argc, argv, &verbosity);

#ifndef NDEBUG
    unsigned ITERATIONS =   3;
    unsigned WARMUPS    =   1;
#else /* ? !NDEBUG */
    unsigned ITERATIONS =   100000;
    unsigned WARMUPS    =   2;
#endif /* !NDEBUG */
    size_t   length     =   0;

    platformstl::performance_counter                counter;
    platformstl::performance_counter::interval_type tm_Streams          =   1;
    platformstl::performance_counter::interval_type tm_IOStreams        =   1;
    platformstl::performance_counter::interval_type tm_CString_Format   =   1;
    platformstl::performance_counter::interval_type tm_Boost            =   1;
    platformstl::performance_counter::interval_type tm_Loki             =   1;
    platformstl::performance_counter::interval_type tm_FF_Format        =   1;
    platformstl::performance_counter::interval_type tm_FF_Write         =   1;

    static const person_t                           args[] =
    {
            {   "Shrek",    6,      1.99f   }
        ,   {   "Batman",   65,     1.87f   }
        ,   {   "Simon",    40,     1.86f   }
        ,   {   "Farman",   40,     1.84f   }
        ,   {   "Marmaduke, Third Lord of the Fleet, Justice of the Provinces, and Emperor of his own back garden", 101,    1.20f   }
    };

    // Test Identifier

    std::string TestId = PANTHEIOS_FE_PROCESS_IDENTITY;

    // IOStreams

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            { for(unsigned k = 0; k != STLSOFT_NUM_ELEMENTS(args); ++k)
            {
#ifdef FASTFORMAT_USE_WIDE_STRINGS
                std::wstringstream   ss;
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
                std::stringstream   ss;
#endif /* FASTFORMAT_USE_WIDE_STRINGS */

                ss << args[k].name << ", " << args[k].age << ", " << args[k].height;

#ifdef FASTFORMAT_USE_WIDE_STRINGS
                std::wstring        s   =   ss.str();
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
                std::string         s   =   ss.str();
#endif /* FASTFORMAT_USE_WIDE_STRINGS */

                length += s.size();
            }}
        }}
        counter.stop();

        tm_IOStreams = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "IOStreams:  %lu\t(%lu)\n", (unsigned long)tm_IOStreams, (unsigned long)length);
        }
    }}

#ifdef FASTFORMAT_PERFTEST_USE_BOOST
    // Boost.Format

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            { for(unsigned k = 0; k != STLSOFT_NUM_ELEMENTS(args); ++k)
            {
                std::string s = boost::str( boost::format("%1%, %2%, %3%") % args[k].name % args[k].age % args[k].height);

                length += s.size();
            }}
        }}
        counter.stop();

        tm_Boost = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "Boost.Format: %lu\t(%lu)\n", (unsigned long)tm_Boost, (unsigned long)length);
        }
    }}
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */

#ifdef FASTFORMAT_PERFTEST_USE_LOKI
    // Loki.SafeFormat

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            { for(unsigned k = 0; k != STLSOFT_NUM_ELEMENTS(args); ++k)
            {
                std::string s;

                Loki::SPrintf(s, ("%s, %d, %g"))(args[k].name)(args[k].age)(args[k].height);

                length += s.size();
            }}
        }}
        counter.stop();

        tm_Loki = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "Loki.SafeFormat: %lu\t(%lu)\n", (unsigned long)tm_Loki, (unsigned long)length);
        }
    }}
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */

#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
    // CString::Format()

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            { for(unsigned k = 0; k != STLSOFT_NUM_ELEMENTS(args); ++k)
            {
                CString s;

                s.Format(TEXT("%s, %d, %g"), args[k].name, args[k].age, args[k].height);

                length += size_t(s.GetLength());
            }}
        }}
        counter.stop();

        tm_CString_Format = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "CString::Format(): %lu\t(%lu)\n", (unsigned long)tm_CString_Format, (unsigned long)length);
        }
    }}

#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
    // sprintf()

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            { for(unsigned k = 0; k != STLSOFT_NUM_ELEMENTS(args); ++k)
            {
                char    sz[1001];
                int     cch = ::sprintf(&sz[0], "%s, %d, %g", args[k].name, args[k].age, args[k].height);

                std::string s(sz, size_t(cch));

                length += s.size();
            }}
        }}
        counter.stop();

        tm_Streams = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "sprintf():  %lu\t(%lu)\n", (unsigned long)tm_Streams, (unsigned long)length);
        }
    }}

    // FastFormat.Format

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            { for(unsigned k = 0; k != STLSOFT_NUM_ELEMENTS(args); ++k)
            {
#ifdef FASTFORMAT_USE_WIDE_STRINGS
                std::wstring    s;
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
                std::string     s;
#endif /* FASTFORMAT_USE_WIDE_STRINGS */

                fastformat::fmt(s, TX("{0}, {1}, {2}"), args[k].name, args[k].age, args[k].height);

                length += s.size();
            }}
        }}
        counter.stop();

        tm_FF_Format = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "FastFormat.Format: %lu\t(%lu)\n", (unsigned long)tm_FF_Format, (unsigned long)length);
        }
    }}

    // FastFormat.Write

    { for(unsigned j = 0; j < WARMUPS; ++j)
    {
        length = 0;
        counter.start();
        { for(unsigned i = 0; i < ITERATIONS; ++i)
        {
            { for(unsigned k = 0; k != STLSOFT_NUM_ELEMENTS(args); ++k)
            {
#ifdef FASTFORMAT_USE_WIDE_STRINGS
                std::wstring    s;
#else /* ? FASTFORMAT_USE_WIDE_STRINGS */
                std::string     s;
#endif /* FASTFORMAT_USE_WIDE_STRINGS */

                fastformat::write(s, args[k].name, ", ", args[k].age, ", ", args[k].height);

                length += s.size();
            }}
        }}
        counter.stop();

        tm_FF_Write = counter.get_microseconds();

        if( verbosity >= 3 &&
            j == WARMUPS - 1)
        {
            ::fprintf(stdout, "FastFormat.Write: %lu\t(%lu)\n", (unsigned long)tm_FF_Write, (unsigned long)length);
        }
    }}

    STLSOFT_SUPPRESS_UNUSED(length);

    std::string     fmt1;
    std::string     fmt2;

    fastformat::ignore_unreferenced_arguments_scope scoper;

    switch(verbosity)
    {
        case    0:
            // no output
            break;
        case    1:
            fmt1 = "";
            fmt1 += "S:FF.F:\t{0}";
            fmt1 += "\tIOS:FF.F:\t{1}";
            fmt1 += "\tFF.W:FF.F:\t{3}";
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            fmt1 += "\tB.F:FF.F:\t{4}";
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            fmt1 += "\tL.SF:FF.F:\t{5}";
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            fmt1 += "\tMFC.F:FF.F:\t{2}";
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
            fastformat::fmtln(  std::cout, fmt1
                            ,   double(tm_Streams) / double(tm_FF_Format)
                            ,   double(tm_IOStreams) / double(tm_FF_Format)
                            ,   double(tm_CString_Format) / double(tm_FF_Format)
                            ,   double(tm_FF_Write) / double(tm_FF_Format)
                            ,   double(tm_Boost) / double(tm_FF_Format)
                            ,   double(tm_Loki) / double(tm_FF_Format));
            fmt1 = "";
            fmt1 += "S:FF.W:\t{0}";
            fmt1 += "\tIOS:FF.W:\t{1}";
            fmt1 += "\tFF.F:FF.W:\t{2}";
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            fmt1 += "\tB.F:FF.W:\t{3}";
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            fmt1 += "\tL.SF:FF.W:\t{3}";
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            fmt1 += "\tMFC.F:FF.W:\t{4}";
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
            fastformat::fmtln(  std::cout, fmt1
                            ,   double(tm_Streams) / double(tm_FF_Write)
                            ,   double(tm_IOStreams) / double(tm_FF_Write)
                            ,   double(tm_CString_Format) / double(tm_FF_Write)
                            ,   double(tm_FF_Format) / double(tm_FF_Write)
                            ,   double(tm_Boost) / double(tm_FF_Write)
                            ,   double(tm_Loki) / double(tm_FF_Write));
            break;
        case    2:
            fastformat::fmtln(std::cout, "{0}\tFastFormat.Format\tFastFormat.Write", TestId);
            fastformat::fmtln(std::cout, "Streams\t{0}\t{1}", double(tm_Streams) / double(tm_FF_Format), double(tm_Streams) / double(tm_FF_Write));
            fastformat::fmtln(std::cout, "IOStreams\t{0}\t{1}", double(tm_IOStreams) / double(tm_FF_Format), double(tm_IOStreams) / double(tm_FF_Write));
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            fastformat::fmtln(std::cout, "CString::Format\t{0}\t{1}", double(tm_CString_Format) / double(tm_FF_Format), double(tm_CString_Format) / double(tm_FF_Write));
#else /* ? FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
            fastformat::writeln(std::cout, "");
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            fastformat::fmtln(std::cout, "Boost.Format\t{0}\t{1}", double(tm_Boost) / double(tm_FF_Format), double(tm_Boost) / double(tm_FF_Write));
#else /* ? FASTFORMAT_PERFTEST_USE_BOOST */
            fastformat::writeln(std::cout, "");
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            fastformat::fmtln(std::cout, "Loki.SafeFormat\t{0}\t{1}", double(tm_Loki) / double(tm_FF_Format), double(tm_Loki) / double(tm_FF_Write));
#else /* ? FASTFORMAT_PERFTEST_USE_LOKI */
            fastformat::writeln(std::cout, "");
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
            fastformat::fmtln(std::cout, "FastFormat.Format\t{0}\t{1}", "", double(tm_FF_Format) / double(tm_FF_Write));
            fastformat::fmtln(std::cout, "FastFormat.Write\t{0}\t{1}", double(tm_FF_Write) / double(tm_FF_Format), "");
            break;
        case    3:
            ::puts("");
            ::fprintf(stdout, "sprintf():FastFormat.Format:         \t%2.04g\n", double(tm_Streams) / double(tm_FF_Format));
            ::fprintf(stdout, "IOStreams:FastFormat.Format:         \t%2.04g\n", double(tm_IOStreams) / double(tm_FF_Format));
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            ::fprintf(stdout, "CString::Format():FastFormat.Format: \t%2.04g\n", double(tm_CString_Format) / double(tm_FF_Format));
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            ::fprintf(stdout, "Boost.Format:FastFormat.Format:      \t%2.04g\n", double(tm_Boost) / double(tm_FF_Format));
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            ::fprintf(stdout, "Loki.SafeFormat:FastFormat.Format:   \t%2.04g\n", double(tm_Loki) / double(tm_FF_Format));
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
            ::puts("");
            ::fprintf(stdout, "sprintf():FastFormat.Write:          \t%2.04g\n", double(tm_Streams) / double(tm_FF_Write));
            ::fprintf(stdout, "IOStreams:FastFormat.Write:          \t%2.04g\n", double(tm_IOStreams) / double(tm_FF_Write));
#ifdef FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING
            ::fprintf(stdout, "CString::Format():FastFormat.Write:  \t%2.04g\n", double(tm_CString_Format) / double(tm_FF_Write));
#endif /* FASTFORMAT_INCL_FASTFORMAT_SINK_HPP_CSTRING */
#ifdef FASTFORMAT_PERFTEST_USE_BOOST
            ::fprintf(stdout, "Boost.Format:FastFormat.Write:       \t%2.04g\n", double(tm_Boost) / double(tm_FF_Write));
#endif /* FASTFORMAT_PERFTEST_USE_BOOST */
#ifdef FASTFORMAT_PERFTEST_USE_LOKI
            ::fprintf(stdout, "Loki.SafeFormat:FastFormat.Write:    \t%2.04g\n", double(tm_Loki) / double(tm_FF_Write));
#endif /* FASTFORMAT_PERFTEST_USE_LOKI */
            ::fprintf(stdout, "\n");
            ::fprintf(stdout, "FastFormat.Format:FastFormat.Write:  \t%2.04g\n", double(tm_FF_Format) / double(tm_FF_Write));
            break;
    }

    return EXIT_SUCCESS;
}

int main(int argc, char *argv[])
{
    int             res;

#if defined(_MSC_VER) && \
    defined(_DEBUG)
    _CrtMemState    memState;
#endif /* _MSC_VER && _MSC_VER */

#if defined(_MSC_VER) && \
    defined(_DEBUG)
    _CrtMemCheckpoint(&memState);
#endif /* _MSC_VER && _MSC_VER */

#if 0
    { for(size_t i = 0; i < 0xffffffff; ++i){} }
#endif /* 0 */

    try
    {
#if defined(_DEBUG) || \
    defined(__SYNSOFT_DBS_DEBUG)
        puts("test.performance.name_age_height: " STLSOFT_COMPILER_LABEL_STRING);
#endif /* debug */

        if(fastformat::init() < 0)
        {
            fprintf(stderr, "Failed to initialise FastFormat\n");

            res = EXIT_FAILURE;
        }
        else
        {
            res = main_(argc, argv);

            fastformat::uninit();
        }
    }
    catch(std::exception& x)
    {
        fprintf(stderr, "Unhandled error: %s\n", x.what());

        res = EXIT_FAILURE;
    }
    catch(...)
    {
        fprintf(stderr, "Unhandled unknown error\n");

        res = EXIT_FAILURE;
    }

#if defined(_MSC_VER) && \
    defined(_DEBUG)
    _CrtMemDumpAllObjectsSince(&memState);
#endif /* _MSC_VER) && _DEBUG */

    return res;
}

/* ///////////////////////////// end of file //////////////////////////// */


text:
CREATE INDEX idx_flowlog_statestatus ON flowlog (statestatus);

CREATE INDEX idx_flowlog_flowid ON flowlog (flowid);

-- //@UNDO
-- SQL to undo the change goes here.

DROP INDEX idx_flowlog_statestatus;

DROP INDEX idx_flowlog_flowid;


text:
namespace common {
namespace rpc {

class ScopedRpcInterfaceRegistration;

}  // namespace rpc
}  // namespace common

namespace kasko {

class Service;

// Establishes an RPC service that forwards requests for the Kasko interface to
// a Service implementation. The Service will be invoked on a worker thread.
//
// Only a single instance of this class may exist at a time in a given process.
class ServiceBridge {
 public:
  // Instantiates a ServiceBridge configured to use |protocol| and |endpoint|
  // and to forwards requests to |service|.
  ServiceBridge(const base::string16& protocol, const base::string16& endpoint,
                scoped_ptr<Service> service);
  ~ServiceBridge();

  // Starts serving requests. Returns immediately. The return value indicates
  // whether the service successfully started.
  //
  // If Run() returns true you _must_ call Stop() before destroying the
  // ServiceBridge.
  bool Run();

  // Stops listening for new requests. Blocks until all in-process requests are
  // handled. It is harmless to call Stop() on a non-running ServiceBridge.
  void Stop();

 private:
  // Without the parentheses the '::' is associated with 'boolean'.
  friend boolean(::KaskoService_SendDiagnosticReport)(  // NOLINT
      handle_t IDL_handle,
      unsigned long exception_info_address,
      unsigned long thread_id,
      ::DumpType dump_type,
      unsigned long protobuf_length,
      const signed char* protobuf,
      unsigned long crash_keys_size,
      const CrashKey* crash_keys);

  scoped_ptr<common::rpc::ScopedRpcInterfaceRegistration>
      interface_registration_;
  scoped_ptr<Service> service_;

  base::string16 protocol_;
  base::string16 endpoint_;
  bool running_;

  DISALLOW_COPY_AND_ASSIGN(ServiceBridge);
};

}  // namespace kasko

#endif  // SYZYGY_KASKO_SERVICE_BRIDGE_H_


text:
package db

import (
	"upper.io/db.v3/lib/sqlbuilder"
	"upper.io/db.v3/postgresql"
)

// Databaser is responsible for housing the Database connection
type Databaser struct {
	Conn sqlbuilder.Database
}

// NewDatabaser returns back a new instance of Databaser
func NewDatabaser(dbURL string) (*Databaser, error) {
	settings, err := postgresql.ParseURL(dbURL)
	if err != nil {
		return nil, err
	}

	sess, err := postgresql.Open(settings)
	if err != nil {
		return nil, err
	}
	return &Databaser{Conn: sess}, nil
}


text:
-- MySQL dump 10.16  Distrib 10.1.13-MariaDB, for Linux (x86_64)
--
-- Host: localhost    Database: vendcrawler
-- ------------------------------------------------------
-- Server version	10.1.13-MariaDB

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `items`
--

DROP TABLE IF EXISTS `items`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `items` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `item_id` int(10) unsigned NOT NULL,
  `item_name` varchar(45) NOT NULL,
  `vendor_id` int(10) unsigned NOT NULL,
  `shop_name` varchar(90) NOT NULL,
  `amount` int(10) unsigned NOT NULL,
  `price` int(10) unsigned NOT NULL,
  `map` varchar(45) NOT NULL,
  `datetime` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `items`
--

LOCK TABLES `items` WRITE;
/*!40000 ALTER TABLE `items` DISABLE KEYS */;
/*!40000 ALTER TABLE `items` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2016-04-21 14:39:43


text:
#ifndef FQZ_COMP_QUAL_H
#define FQZ_COMP_QUAL_H

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>

/* Bit flags, deliberately mirroring BAM ones */
#define FQZ_FREVERSE 16
#define FQZ_FREAD2 128

/* Current FQZ format version */
#define FQZ_VERS 5

#define FQZ_MAX_STRAT 3

/*
 * Minimal per-record information taken from a cram slice.
 *
 * To compress we need to know the junction from one quality string to
 * the next (len), whether it is first/second read and whether it is
 * reverse complemented (flags).
 */
typedef struct {
    int num_records;
    uint32_t *len;    // of size num_records
    uint32_t *flags;  // of size num_records
} fqz_slice;

// Global flags
static const int GFLAG_MULTI_PARAM = 1;
static const int GFLAG_HAVE_STAB   = 2;
static const int GFLAG_DO_REV      = 4;

// Param flags
// Add PFLAG_HAVE_DMAP and a dmap[] for delta incr?
static const int PFLAG_DO_DEDUP    = 2;
static const int PFLAG_DO_LEN      = 4;
static const int PFLAG_DO_SEL      = 8;
static const int PFLAG_HAVE_QMAP   = 16;
static const int PFLAG_HAVE_PTAB   = 32;
static const int PFLAG_HAVE_DTAB   = 64;
static const int PFLAG_HAVE_QTAB   = 128;

/*
 * FQZ parameters.  These may be simply passed in as NULL to fqz_compress
 * and it'll automatically choose, but if we wish to have complete control
 * then this (long) struct contains all the details.
 *
 * TODO: document all this!
 */

// A single parameter block
typedef struct {
    // Starting context value
    uint16_t context;

    // flags
    unsigned int pflags;
    unsigned int do_sel, do_dedup, store_qmap, fixed_len;
    unsigned char use_qtab, use_dtab, use_ptab;

    // context bits and locations
    unsigned int qbits, qloc;
    unsigned int pbits, ploc;
    unsigned int dbits, dloc;
    unsigned int sbits, sloc;

    // models
    int max_sym, nsym, max_sel;

    // tables / maps
    unsigned int qmap[256];
    unsigned int qtab[256];
    unsigned int ptab[1024];
    unsigned int dtab[256];

    // Not stored paramters, but computed as part of encoder
    // parameterisation.
    int qshift;
    int pshift;
    int dshift;
    int sshift;
    unsigned int qmask; // (1<<qbits)-1
    int do_r2, do_qa;
} fqz_param;

// The global params, which is a collection of parameter blocks plus
// a few pieces of meta-data.
typedef struct {
    int vers;               // Format version; Set to FQZ_VERS
    unsigned int gflags;    // global param flags
    int nparam;             // Number of fqz_param blocks
    int max_sel;            // Number of selector values
    unsigned int stab[256]; // Selector to parameter no. table

    int max_sym;            // max symbol value across all sub-params

    fqz_param *p;           // 1 or more parameter blocks
} fqz_gparams;

/** Compress a block of quality values.
 *
 * @param vers          The CRAM version number (<<8) plus fqz strategy (0-3)
 * @param s             Length and flag data CRAM per-record
 * @param in            Buffer of concatenated quality values (no separator)
 * @param in_size       Size of in buffer
 * @param out_size      Size of returned output
 * @param strat         FQZ compression strategy (0 to FQZ_MAX_STRAT)
 * @param gp            Optional fqzcomp paramters (may be NULL).
 *
 * @return              The compressed quality buffer on success,
 *                      NULL on failure.
 */
char *fqz_compress(int vers, fqz_slice *s, char *in, size_t in_size,
                   size_t *out_size, int strat, fqz_gparams *gp);

/** Decompress a block of quality values.
 *
 * @param in            Buffer of compressed quality values
 * @param in_size       Size of in buffer
 * @param out_size      Size of returned output
 * @param lengths       Optional array filled out with record lengths.
 *                      May be NULL.  If not, preallocate it to correct size.
 *
 * @return              The uncompressed concatenated qualities on success,
 *                      NULL on failure.
 */
char *fqz_decompress(char *in, size_t in_size, size_t *out_size,
                     int *lengths, int nlengths);

/** A utlity function to analyse a quality buffer to gather statistical
 *  information.  This is written into qhist and pm.  This function is only
 *  useful if you intend on passing your own fqz_gparams block to
 *  fqz_compress.
 */
void fqz_qual_stats(fqz_slice *s,
                    unsigned char *in, size_t in_size,
                    fqz_param *pm,
                    uint32_t qhist[256],
                    int one_param);

#ifdef __cplusplus
}
#endif

#endif


text:
<!DOCTYPE html>

<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charset="utf-8">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta name="generator" content="Hugo 0.57.2" />
<meta property="og:title" content="SRE Principles" />
<meta name="twitter:title" content="SRE Principles"/>
<meta itemprop="name" content="SRE Principles"><meta property="og:description" content="As Ben Treynor (VP of 24x7 at Google and founding father of SRE) puts it, “SRE, fundamentally, it's what happens when you ask a software engineer to design an operations function”. What does differentiate an SRE (Site Reliability Engineering) from DevOps? Aren’t they the same?
SRE is a job function that focuses on the reliability and maintainability of systems. It is also a mindset and a set of engineering practices to run better production services." />
  <meta name="twitter:description" content="As Ben Treynor (VP of 24x7 at Google and founding father of SRE) puts it, “SRE, fundamentally, it's what happens when you ask a software engineer to design an operations function”. What does differentiate an SRE (Site Reliability Engineering) from DevOps? Aren’t they the same?
SRE is a job function that focuses on the reliability and maintainability of systems. It is also a mindset and a set of engineering practices to run better production services." />
  <meta itemprop="description" content="As Ben Treynor (VP of 24x7 at Google and founding father of SRE) puts it, “SRE, fundamentally, it's what happens when you ask a software engineer to design an operations function”. What does differentiate an SRE (Site Reliability Engineering) from DevOps? Aren’t they the same?
SRE is a job function that focuses on the reliability and maintainability of systems. It is also a mindset and a set of engineering practices to run better production services."><meta name="twitter:site" content="@devopsdays">
<meta property="og:type" content="talk" />
<meta property="og:url" content="/events/2018-zurich/program/ramon-medrano-llamas/" /><meta name="twitter:creator" content="@DevOpsZH" /><meta name="twitter:label1" value="Event" />
  <meta name="twitter:data1" value="devopsdays Zürich 2018" /><meta name="twitter:label2" value="Dates" />
    <meta name="twitter:data2" value="May 2 - 3, 2018" /><meta property="og:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta itemprop="image" content="https://www.devopsdays.org/img/sharing.jpg" />
<meta property="fb:app_id" content="1904065206497317" /><meta itemprop="wordCount" content="128">
<title>SRE Principles - devopsdays Zürich 2018
</title>

<link href="/css/site.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed:300,400,700" rel="stylesheet"><link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192"  href="/android-icon-192x192.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">

      <link href="/events/index.xml" rel="alternate" type="application/rss+xml" title="DevOpsDays" />
      <link href="/events/index.xml" rel="feed" type="application/rss+xml" title="DevOpsDays" />

  DevOpsDays

<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

</button>

events

blog

sponsor

speaking

organizing

about

  Zürich
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar2">

</button>

                  speakers

                  program

                  location

                  registration

                  sponsor

                  Ladies Night

                  contact

                  conduct

SRE Principles

As Ben Treynor (VP of 24x7 at Google and founding father of SRE) puts it, “SRE,
fundamentally, it's what happens when you ask a software engineer to design an operations
function”. What does differentiate an SRE (Site Reliability Engineering) from DevOps?
Aren’t they the same?

SRE is a job function that focuses on the reliability and maintainability of systems. It
is also a mindset and a set of engineering practices to run better production services. An
SRE has to be able to engineer creative solutions to problems, strike the right balance
between reliability and feature velocity and target appropriate levels of service quality.

This talk will cover the principles under which all SRE teams operate at Google:
consistency, design of systems, monitoring, automation, error budgets, blameless
postmortems, etc.

Speaker

            Ramón Medrano Llamas

          Ramón Medrano Llamas is a site reliability engineering manager at Google, focused on the
Identity and User teams. He concentrates on the reliability aspects of new Google products
and new features of ...

Evening Event Sponsors

Gold Sponsors

Silver Sponsors

Bronze Sponsors
Join as Bronze Sponsor!

Community Sponsors
Join as Community Sponsor!

@DEVOPSDAYS

BLOG

10 years of devopsdays

by Kris Buytaert - 10 May, 2019

It’s hard to believe but it is almost 10 years ago since #devopsdays happened for the first time in Gent. Back then there were almost 70 of us talking about topics that were of interest to both Operations and Development, we were exchanging our ideas and experiences `on how we were improving the quality of software delivery.
Our ideas got started on the crossroads of Open Source, Agile and early Cloud Adoption.

Blogs

10 May, 2019

Feed

CFP OPEN
Campinas
Macapá
Shanghai
Recife
Charlotte
Prague
Tokyo
Salt Lake City

Propose a talk at an event near you!

About

    devopsdays is a worldwide community conference series for anyone interested in IT improvement.

    About devopsdays

    Privacy Policy

    Code of Conduct


text:
title: Software components
overview: The software elements that come together within the SLATE platform

order: 80

layout: docs2020
type: markdown
---

{% include section-index.html %}


text:
package org.apache.phoenix.iterate;

import java.sql.SQLException;
import java.util.List;

import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.expression.Expression;
import org.apache.phoenix.expression.OrderByExpression;
import org.apache.phoenix.schema.tuple.Tuple;

/**
 *
 * ResultIterator that does a merge sort on the list of iterators provided,
 * returning the rows ordered by the OrderByExpression. The input
 * iterators must be ordered by the OrderByExpression.
 *
 *
 * @since 0.1
 */
public class MergeSortTopNResultIterator extends MergeSortResultIterator {

    private final int limit;
    private int count = 0;
    private final List<OrderByExpression> orderByColumns;
    private final ImmutableBytesWritable ptr1 = new ImmutableBytesWritable();
    private final ImmutableBytesWritable ptr2 = new ImmutableBytesWritable();

    public MergeSortTopNResultIterator(ResultIterators iterators, Integer limit, List<OrderByExpression> orderByColumns) {
        super(iterators);
        this.limit = limit == null ? -1 : limit;
        this.orderByColumns = orderByColumns;
    }

    @Override
    protected int compare(Tuple t1, Tuple t2) {
        for (int i = 0; i < orderByColumns.size(); i++) {
            OrderByExpression order = orderByColumns.get(i);
            Expression orderExpr = order.getExpression();
            boolean isNull1 = !orderExpr.evaluate(t1, ptr1) || ptr1.getLength() == 0;
            boolean isNull2 = !orderExpr.evaluate(t2, ptr2) || ptr2.getLength() == 0;
            if (isNull1 && isNull2) {
                continue;
            } else if (isNull1) {
                return order.isNullsLast() ? 1 : -1;
            } else if (isNull2) {
                return order.isNullsLast() ? -1 : 1;
            }
            int cmp = ptr1.compareTo(ptr2);
            if (cmp == 0) {
                continue;
            }
            return order.isAscending() ? cmp : -cmp;
        }
        return 0;
    }

    @Override
    public Tuple peek() throws SQLException {
        if (limit >= 0 && count >= limit) {
            return null;
        }
        return super.peek();
    }

    @Override
    public Tuple next() throws SQLException {
        if (limit >= 0 && count++ >= limit) {
            return null;
        }
        return super.next();
    }

    @Override
    public void explain(List<String> planSteps) {
        resultIterators.explain(planSteps);
        planSteps.add("    SERVER" + (limit == -1 ? "" : " TOP " + limit + " ROW" + (limit == 1 ? "" : "S")) + " SORTED BY " + orderByColumns.toString());
        planSteps.add("CLIENT MERGE SORT");
    }
}


text:
if [ -z "$1" ]; then
  _env="dev"
else
  _env=$1
fi

if [ $_env = "dev" ]; then
  node server.js
elif [ $_env = 'prod' ]; then
  webpack --colors --progress --display-error-details --env prod
elif [ $_env = 'test' ]; then
  webpack --colors --progress --display-error-details --env test
else
  echo 'unknown env'
fi


text:
package de.ks.strudel.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

public class DeleteDir {
  private final File dir;

  public DeleteDir(File dir) {
    this.dir = dir;
  }

  public DeleteDir(Path path) {
    this.dir = path.toFile();
  }

  public void delete() {
    if (dir == null || !dir.exists()) {
      return;
    }
    try {
      deleteDir(dir);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  protected void deleteDir(File file) throws IOException {
    Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        Files.delete(file);
        return FileVisitResult.CONTINUE;
      }

      @Override
      public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        Files.delete(dir);
        return FileVisitResult.CONTINUE;
      }
    });
  }
}


text:
pub struct Referer(pub String);

impl_header!(Referer,
             "Referer",
             String);

bench_header!(bench, Referer, { vec![b"http://foo.com/hello:3000".to_vec()] });


text:
require 'rails_helper'

RSpec.describe GithubWebhooksController, :type => :controller do

end


text:
var assert = require('assert');
var path = require('path');
var ComponentHint = require('../lib/component-hint.js');

//
var casePath = './tests/cases';
function resolveCasePath(caseName, componentPath) {
	return path.resolve(casePath, caseName, componentPath);
}

//
describe('ComponentHint Class', function () {
	it('could create instance', function () {
		new ComponentHint();
	});

	it('could load component data', function (done) {
		var componentHint = new ComponentHint();
		componentHint.loadComponentData(resolveCasePath('case-clean', 'component_A'), false, function (error, data) {
			assert.ifError(error, 'ComponentHint#loadComponentData returned an error');

			assert.deepEqual(data, {
				path: resolveCasePath('case-clean', 'component_A'),
				json: {
					name: 'component_A',
					dependencies: { dependencyA: '*', dependencyB: '*'},
					local: ['component_B'],
					paths: ['..'],
					styles: [],
					scripts: []
				},
				channel: 'lint.error'
			}, 'ComponentHint#loadComponentData returned incorrect data');

			done();
		});
	});

	it('could load recursively', function (done) {
		var componentHint = new ComponentHint({
			depPaths: resolveCasePath('case-clean', 'components'),
			recursive: true
		});

		componentHint.checkPaths(resolveCasePath('case-clean', 'component_A'), false, function () {
			assert.equal(componentHint.lintedComponents.length, 4, 'ComponentHint#checkPaths didn\'t load all components & dependencies');
			done();
		});
	});
});


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Graduate Research Fellowship Program (GRFP)</AwardTitle>
    <AwardEffectiveDate>07/01/2016</AwardEffectiveDate>
    <AwardExpirationDate>06/30/2021</AwardExpirationDate>
    <AwardAmount>1074000</AwardAmount>
    <AwardInstrument>
      <Value>Fellowship</Value>
    </AwardInstrument>
    <Organization>
      11010101
      <Directorate>
        <LongName>Direct For Education and Human Resources</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Graduate Education</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Gisele T. Muller-Parker</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>The National Science Foundation (NSF) Graduate Research Fellowship Program (GRFP) is a highly competitive, federal fellowship program. GRFP helps ensure the vitality and diversity of the scientific and engineering workforce of the United States. The program recognizes and supports outstanding graduate students who are pursuing research-based master's and doctoral degrees in science, technology, engineering, and mathematics (STEM) and in STEM education. The GRFP provides three years of financial support for the graduate education of individuals who have demonstrated their potential for significant research achievements in STEM and STEM education. This award supports the NSF Graduate Fellows pursuing graduate education at this GRFP institution.</AbstractNarration>
    <MinAmdLetterDate>06/25/2016</MinAmdLetterDate>
    <MaxAmdLetterDate>09/14/2016</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1644760</AwardID>
    <Investigator>
      <FirstName>Peter</FirstName>
      <LastName>Weber</LastName>
      <EmailAddress>Peter_Weber@Brown.edu</EmailAddress>
      <StartDate>06/25/2016</StartDate>
      <EndDate>09/14/2016</EndDate>
      <RoleCode>Former Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Andrew</FirstName>
      <LastName>Campbell</LastName>
      <EmailAddress>andrew_campbell@brown.edu</EmailAddress>
      <StartDate>09/14/2016</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Brown University</Name>
      <CityName>Providence</CityName>
      <ZipCode>029129002</ZipCode>
      <PhoneNumber>4018632777</PhoneNumber>
      <StreetAddress>BOX 1929</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Rhode Island</StateName>
      <StateCode>RI</StateCode>
    </Institution>
    <ProgramElement>
      7172
      <Text>GRADUATE RESEARCH FELLOWSHIPS</Text>
    </ProgramElement>
    <ProgramReference>
      7172
      <Text>GRADUATE FELLOWSHIPS</Text>
    </ProgramReference>
    <ProgramReference>
      9179
      <Text>GRADUATE INVOLVEMENT</Text>
    </ProgramReference>
    <ProgramReference>
      SMET
      <Text>SCIENCE, MATH, ENG & TECH EDUCATION</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
/**
 * Contains examples about the Annotation Based Configuration topic.
 */
package com.tutorialspoint.annotationbasedconfiguration;


text:
package sadCycles;

public class Tester {

	/**
	 * Tester for SadCycles
	 */
	public static void main(String[] args) {

		SadCycles.sadCycles(12, 2);

		SadCycles.sadCycles(117649, 5);

	}

}