text:
BSLS_IDENT_RCSID(ball_asyncfileobserver_cpp,"$Id$ $CSID$")

#include <ball_log.h>                         // for testing only
#include <ball_loggermanager.h>               // for testing only
#include <ball_loggermanagerconfiguration.h>  // for testing only
#include <ball_streamobserver.h>              // for testing only

#include <bdlf_bind.h>
#include <bdlf_memfn.h>
#include <bdls_processutil.h>
#include <bdlt_currenttime.h>

#include <bslma_default.h>
#include <bslmt_lockguard.h>
#include <bslmt_mutexassert.h>
#include <bslmt_threadattributes.h>

#include <bsls_assert.h>

#include <bsl_functional.h>
#include <bsl_memory.h>
#include <bsl_ostream.h>

///IMPLEMENTATION NOTES
///--------------------
// To communicate the last record to be published when 'stopThread' (or
// 'stopPublicationThread') is called, a special record is enqueued (created using
// 'createStopRecord') for which 'isStopRecord' is 'false'.

namespace BloombergLP {
namespace ball {

namespace {

enum {
    k_DEFAULT_FIXED_QUEUE_SIZE = 8192,
    k_FORCE_WARN_THRESHOLD     = 5000
};

static const char *const k_LOG_CATEGORY = "BALL.ASYNCFILEOBSERVER";

static const char *const k_THREAD_NAME = "asyncobserver";

bsl::shared_ptr<ball::Record> createEmptyRecord(
                                              int                   lineNumber,
                                              ball::Severity::Level level)
{
    bsl::shared_ptr<ball::Record> record = bsl::make_shared<ball::Record>();
    record->fixedFields().setFileName(__FILE__);
    record->fixedFields().setCategory(k_LOG_CATEGORY);
    record->fixedFields().setSeverity(level);
    record->fixedFields().setProcessID(bdls::ProcessUtil::getProcessId());
    record->fixedFields().setLineNumber(lineNumber);
    record->fixedFields().setTimestamp(bdlt::CurrentTime::utc());
    record->fixedFields().setThreadID(bslmt::ThreadUtil::selfIdAsUint64());

    return record;
}

void logDroppedMessageWarning(ball::FileObserver *fileObserver, int numDropped)
    // Publish a record to the specified 'fileObserver' at 'WARN' severity
    // level that the specified 'numDropped' messages have been dropped from
    // publication because they could not be enqueued on the async file
    // observer.
{
    // We log the record unconditionally (i.e., without consulting the logger
    // manager as to whether WARN is enabled) to avoid an
    // observer->loggermanager dependency.

    bsl::shared_ptr<ball::Record> record =
        createEmptyRecord(__LINE__, ball::Severity::e_WARN);

    bsl::ostream os(&record->fixedFields().messageStreamBuf());
    os << "Dropped " << numDropped << " log records." << bsl::ends;

    Context context(Transmission::e_PASSTHROUGH, 0, 0);
    fileObserver->publish(record, context);
}

void logQueueFailureError(ball::FileObserver *fileObserver)
    // Publish a record to the specified 'fileObserver' at 'ERROR' severity
    // level indicating a failure to dequeue methods off of the async file
    // observers record queue.
{
    // We log the record unconditionally (i.e., without consulting the logger
    // manager as to whether ERROR is enabled) to avoid an
    // observer->loggermanager dependency.

    bsl::shared_ptr<ball::Record> record =
        createEmptyRecord(__LINE__, ball::Severity::e_ERROR);

    bsl::ostream os(&record->fixedFields().messageStreamBuf());
    os << "Unable to dequeue messages for asynchronous publication. "
       << "Stopping asynchronous publication and dropping all messages.";

    Context context(Transmission::e_PASSTHROUGH, 0, 0);
    fileObserver->publish(record, context);
}

void logReleaseRecordsError(ball::FileObserver *fileObserver)
    // Publish a record to the specified 'fileObserver' at 'ERROR' severity
    // level indicating a failure in flushing the queue as part of release
    // records.
{
    // We log the record unconditionally (i.e., without consulting the logger
    // manager as to whether ERROR is enabled) to avoid an
    // observer->loggermanager dependency.

    bsl::shared_ptr<ball::Record> record =
        createEmptyRecord(__LINE__, ball::Severity::e_ERROR);

    bsl::ostream os(&record->fixedFields().messageStreamBuf());
    os << "'releaseRecords' unable to restart the publication thread.";

    Context context(Transmission::e_PASSTHROUGH, 0, 0);
    fileObserver->publish(record, context);
}

void setPublicationThreadAttributes(bslmt::ThreadAttributes *attributes)
    // Load the specified 'attributes' with the attributes for the publication
    // thread (for the moment, the thread name).
{
    attributes->setThreadName(k_THREAD_NAME);
}

        // stop-record functions

AsyncFileObserver_Record createStopRecord()
    // Return a 'AsyncFileObserver_Record' object for which 'isStopRecord' will
    // return 'true', and that cannot be a user created record from
    // 'ball::AsyncFileObserver::publish'.  Note that this record is used by
    // 'stopThread' to signal to the publication thread to stop.  Note also that
    // this is not simply a constant because such a constant would require a
    // constructor be called before 'main' in C++03.
{
    AsyncFileObserver_Record record;
    return record;
}

bool isStopRecord(const AsyncFileObserver_Record& record)
    // Return 'true' if the specified 'record' was created by
    // 'createStopRecord' and 'false' otherwise.  Note that this record is used
    // by 'stopThread' to signal to the publication thread to stop.
{
    return 0 == record.d_record.get();
}

}  // close unnamed namespace

                       // -----------------------
                       // class AsyncFileObserver
                       // -----------------------

void AsyncFileObserver::publishThreadEntryPoint()
{
    typedef bdlcc::BoundedQueue<AsyncFileObserver_Record> Status;

    // The publication thread may either be 'e_RUNNING' (normal), or
    // 'e_SHUTTING_DOWN' (if a client called a method that stopped the
    // publication thread immediately after starting it, before this thread
    // entry point function is called).  The publication cannot be
    // 'e_NOT_RUNNING', since that state is only returned to after completing
    // this function.

    BSLS_ASSERT(e_RUNNING == d_threadState);

    bool done = false;

    while (!done) {
        AsyncFileObserver_Record record;

        int rc = d_recordQueue.popFront(&record);

        BSLS_ASSERT(0 == rc
                 || Status::e_DISABLED == rc
                 || Status::e_FAILED   == rc);

        if (Status::e_SUCCESS == rc && !isStopRecord(record)) {
            d_fileObserver.publish(record.d_record, record.d_context);
        }
        else {
            done = true;
        }

        // Publish the count of dropped records.  To avoid repeatedly
        // publishing this information when the record queue is full, we
        // publish the number of dropped records only when the queue becomes
        // half empty or when a sufficient number of records have been dropped.
        // Finally, we publish the dropped record count if the observer is
        // shutting down, so the information is not lost.

        if (0 < d_dropCount.loadRelaxed()) {
            if (d_recordQueue.numElements() <= d_recordQueue.numElements() / 2
            ||  d_dropCount.loadRelaxed()   >= k_FORCE_WARN_THRESHOLD
            ||  done) {
                int numDropped = d_dropCount.swap(0);
                BSLS_ASSERT(0 < numDropped); // No other thread should have
                                             // cleared the count.
                logDroppedMessageWarning(&d_fileObserver, numDropped);
            }
        }

        if (Status::e_FAILED == rc) {
            // This is likely a catastrophic unrecoverable error, and one which
            // is very difficult to simular in testing.  There may be
            // "stop-records" still in the queue, rather than adding a
            // complicated mechanism handle them, it is simpler to just empty
            // the queue.

            logQueueFailureError(&d_fileObserver);
            d_recordQueue.removeAll();
        }
    }
    d_threadState = e_NOT_RUNNING;
}

void AsyncFileObserver::construct()
{
    d_threadHandle = bslmt::ThreadUtil::invalidHandle();
    d_threadState  = e_NOT_RUNNING;
    d_dropCount    = 0;

    d_publishThreadEntryPoint = bsl::function<void()>(
            bsl::allocator_arg_t(),
            bsl::allocator<bsl::function<void()> >(d_allocator_p),
            bdlf::MemFnUtil::memFn(&AsyncFileObserver::publishThreadEntryPoint,
                                   this));
}

// CREATORS
AsyncFileObserver::AsyncFileObserver(bslma::Allocator *basicAllocator)
: d_fileObserver(Severity::e_WARN, basicAllocator)
, d_recordQueue(k_DEFAULT_FIXED_QUEUE_SIZE, basicAllocator)
, d_threadState(e_NOT_RUNNING)
, d_dropRecordsOnFullQueueThreshold(Severity::e_OFF)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
{
    construct();
}

AsyncFileObserver::AsyncFileObserver(Severity::Level   stdoutThreshold,
                                     bslma::Allocator *basicAllocator)
: d_fileObserver(stdoutThreshold, basicAllocator)
, d_recordQueue(k_DEFAULT_FIXED_QUEUE_SIZE, basicAllocator)
, d_threadState(e_NOT_RUNNING)
, d_dropRecordsOnFullQueueThreshold(Severity::e_OFF)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
{
    construct();
}

AsyncFileObserver::AsyncFileObserver(Severity::Level   stdoutThreshold,
                                     bool              publishInLocalTime,
                                     bslma::Allocator *basicAllocator)
: d_fileObserver(stdoutThreshold, publishInLocalTime, basicAllocator)
, d_recordQueue(k_DEFAULT_FIXED_QUEUE_SIZE, basicAllocator)
, d_threadState(e_NOT_RUNNING)
, d_dropRecordsOnFullQueueThreshold(Severity::e_OFF)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
{
    construct();
}

AsyncFileObserver::AsyncFileObserver(Severity::Level   stdoutThreshold,
                                     bool              publishInLocalTime,
                                     int               maxRecordQueueSize,
                                     bslma::Allocator *basicAllocator)
: d_fileObserver(stdoutThreshold, publishInLocalTime, basicAllocator)
, d_recordQueue(maxRecordQueueSize, basicAllocator)
, d_threadState(e_NOT_RUNNING)
, d_dropRecordsOnFullQueueThreshold(Severity::e_OFF)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
{
    construct();
}

AsyncFileObserver::AsyncFileObserver(
                             Severity::Level   stdoutThreshold,
                             bool              publishInLocalTime,
                             int               maxRecordQueueSize,
                             Severity::Level   dropRecordsOnFullQueueThreshold,
                             bslma::Allocator *basicAllocator)
: d_fileObserver(stdoutThreshold, publishInLocalTime, basicAllocator)
, d_recordQueue(maxRecordQueueSize, basicAllocator)
, d_threadState(e_NOT_RUNNING)
, d_dropRecordsOnFullQueueThreshold(dropRecordsOnFullQueueThreshold)
, d_allocator_p(bslma::Default::allocator(basicAllocator))
{
    construct();
}

AsyncFileObserver::~AsyncFileObserver()
{
    stopPublicationThread();
}

// MANIPULATORS
void AsyncFileObserver::publish(const bsl::shared_ptr<const Record>& record,
                                const Context&                       context)
{
    BSLS_ASSERT(record);

    AsyncFileObserver_Record asyncRecord;

    asyncRecord.d_record  = record;
    asyncRecord.d_context = context;

    int rc = (record->fixedFields().severity() > d_dropRecordsOnFullQueueThreshold)
      ? d_recordQueue.tryPushBack(asyncRecord)
      : d_recordQueue.pushBack(asyncRecord);

    if (0 != rc) {
      d_dropCount.addRelaxed(1);
    }

}

void AsyncFileObserver::releaseRecords()
{
    bslmt::LockGuard<bslmt::Mutex> guard(&d_mutex);
    if (isPublicationThreadRunning()) {
        d_recordQueue.disablePopFront();

        // If either destroying or creating the publicaiton thread fails, it is
        // a catastrophic error.

        int rc = bslmt::ThreadUtil::join(d_threadHandle);

        if (0 != rc) {
            logReleaseRecordsError(&d_fileObserver);
            return;                                                   // RETURN
        }

        d_recordQueue.removeAll();

        d_threadState = e_RUNNING;
        d_recordQueue.enablePopFront();

        bslmt::ThreadAttributes attr;
        setPublicationThreadAttributes(&attr);
        rc = bslmt::ThreadUtil::create(
            &d_threadHandle, attr, d_publishThreadEntryPoint);

        if (0 != rc) {
            logReleaseRecordsError(&d_fileObserver);
        }
    }
    else {
        d_recordQueue.removeAll();
    }
}

int AsyncFileObserver::shutdownPublicationThread()
{
    bslmt::LockGuard<bslmt::Mutex> guard(&d_mutex);

    BSLMT_MUTEXASSERT_IS_LOCKED(&d_mutex);

    // d_threadState and d_threadHandle should be consistent.

    BSLS_ASSERT((e_NOT_RUNNING == d_threadState) ==
                (bslmt::ThreadUtil::invalidHandle() == d_threadHandle));

    int result = 0;

    if (bslmt::ThreadUtil::invalidHandle() != d_threadHandle) {
        BSLS_ASSERT(e_RUNNING == d_threadState);

        d_recordQueue.disablePopFront();

        result = bslmt::ThreadUtil::join(d_threadHandle);
        d_threadHandle = bslmt::ThreadUtil::invalidHandle();

    }

    // The lock on 'd_mutex' should prevent any other thread from modifying
    // 'd_threadState' after the thread is stopped, so 'd_threadState'
    // and 'd_threadHandle' should be consistent.

    BSLS_ASSERT(e_NOT_RUNNING == d_threadState);
    BSLS_ASSERT(bslmt::ThreadUtil::invalidHandle() == d_threadHandle);

    return result;
}

int AsyncFileObserver::startPublicationThread()
{
    bslmt::LockGuard<bslmt::Mutex> guard(&d_mutex);

    // d_threadState and d_threadHandle should be consistent.

    BSLS_ASSERT((e_NOT_RUNNING == d_threadState) ==
                (bslmt::ThreadUtil::invalidHandle() == d_threadHandle));

    int result = 0;

    if (bslmt::ThreadUtil::invalidHandle() == d_threadHandle) {
        BSLS_ASSERT(e_NOT_RUNNING == d_threadState);

        d_threadState = e_RUNNING;
        d_recordQueue.enablePopFront();

        bslmt::ThreadAttributes attr;
        setPublicationThreadAttributes(&attr);
        result = bslmt::ThreadUtil::create(&d_threadHandle,
                                           attr,
                                           d_publishThreadEntryPoint);
                                                               // RETURN
    }
    return result;
}

int AsyncFileObserver::stopPublicationThread()
{
    bslmt::LockGuard<bslmt::Mutex> guard(&d_mutex);

    typedef bdlcc::BoundedQueue<AsyncFileObserver_Record> Status;

    BSLMT_MUTEXASSERT_IS_LOCKED(&d_mutex);

    // d_threadState and d_threadHandle should be consistent.

    BSLS_ASSERT((e_NOT_RUNNING == d_threadState) ==
                (bslmt::ThreadUtil::invalidHandle() == d_threadHandle));

    int result = 0;
    if (bslmt::ThreadUtil::invalidHandle() != d_threadHandle) {
        BSLS_ASSERT(e_RUNNING == d_threadState);

        AsyncFileObserver_Record asyncRecord = createStopRecord();
        {
            // We use 'tryPushBack' because we do not want 'pushBack' to block
            // if queue is full, particulary if the publication thread has
            // already observed 'e_SHUTTING_DOWN' and has stopped removing
            // records from the queue (DRQS 164688087), as may happen on a call
            // to 'shutdownThread'.

            int rc;
            do {
                rc = d_recordQueue.tryPushBack(asyncRecord);
                bslmt::ThreadUtil::yield();
            } while (Status::e_FULL == rc && d_threadState != e_NOT_RUNNING);
        }
        result = bslmt::ThreadUtil::join(d_threadHandle);
        d_threadHandle = bslmt::ThreadUtil::invalidHandle();
    }

    BSLS_ASSERT(e_NOT_RUNNING == d_threadState);
    BSLS_ASSERT(bslmt::ThreadUtil::invalidHandle() == d_threadHandle);

    return result;
}

}  // close package namespace
}  // close enterprise namespace

// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" />
	<meta content="2013-12-25 10:18:47 -0700" http-equiv="change-date" />
	<title>EC 8</title>

	<link rel="stylesheet" href='../css/bpi.css' >

Eclesiastes 8

1Quem é como o sábio? e quem sabe a interpretação das coisas? A sabedoria do homem faz brilhar o seu rosto, e com ela a dureza do seu rosto se transforma.

2Eu digo: Observa o mandamento do rei, e isso por causa do juramento a Deus.

3Não te apresses a sair da presença dele; nem persistas em alguma coisa má; porque ele faz tudo o que lhe agrada.

4Porque a palavra do rei é suprema; e quem lhe dirá: que fazes?

5Quem guardar o mandamento não experimentará nenhum mal; e o coração do sábio discernirá o tempo e o juízo.

6Porque para todo propósito há tempo e juízo; porquanto a miséria do homem pesa sobre ele.

7Porque não sabe o que há de suceder; pois quem lho dará a entender como há de ser?

8Nenhum homem há que tenha domínio sobre o espírito, para o reter; nem que tenha poder sobre o dia da morte; nem há licença em tempo de guerra; nem tampouco a impiedade livrará aquele que a ela está entregue.

9Tudo isto tenho observado enquanto aplicava o meu coração a toda obra que se faz debaixo do sol; tempo há em que um homem tem domínio sobre outro homem para o seu próprio dano.

10Vi também os ímpios sepultados, os que antes entravam e saíam do lugar santo; e foram esquecidos na cidade onde haviam assim procedido; também isso é vaidade.

11Porquanto não se executa logo o juízo sobre a má obra, o coração dos filhos dos homens está inteiramente disposto para praticar o mal.

12Ainda que o pecador faça o mal cem vezes, e os dias se lhe prolonguem, contudo eu sei com certeza que bem sucede aos que temem a Deus, porque temem diante dele;

13ao ímpio, porém, não irá bem, e ele não prolongará os seus dias, que são como a sombra; porque ele não teme diante de Deus.

14Ainda há outra vaidade que se faz sobre a terra: há justos a quem sucede segundo as obras dos ímpios, e há ímpios a quem sucede segundo as obras dos justos. Eu disse que também isso é vaidade.

15Exalto, pois, a alegria, porquanto o homem nenhuma coisa melhor tem debaixo do sol do que comer, beber e alegrar-se; porque isso o acompanhará no seu trabalho nos dias da sua vida que Deus lhe dá debaixo do sol.

16Quando apliquei o meu coração a conhecer a sabedoria, e a ver o trabalho que se faz sobre a terra {pois homens há que nem de dia nem de noite conseguem dar sono aos seus olhos},

17então contemplei toda obra de Deus, e vi que o homem não pode compreender a obra que se faz debaixo do sol; pois por mais que o homem trabalhe para a descobrir, não a achará; embora o sábio queira conhecê-la, nem por isso a poderá compreender.

Almeida Revista e Atualizada© Copyright © 1993 Sociedade Bíblica do Brasil. Todos os direitos reservados. Texto bíblico utilizado com autorização. Saiba mais sobre a Sociedade Bíblica do Brasil. A Sociedade Bíblica do Brasil trabalha para que a Bíblia esteja, efetivamente, ao alcance de todos e seja lida por todos. A SBB é uma entidade sem fins lucrativos, dedicada a promover o desenvolvimento integral do ser humano.

redpajama_set_name: RedPajamaGithub


text:
from django.conf.urls import url

from .views import LaunchView, ConfigView, ReturnRedirectView

urlpatterns = [
    url(r'^testlaunch', LaunchView.as_view(), name='testlaunch'),
    url(r'^config/(?P<slug>\w+)/$',
        ConfigView.as_view(template_name='config.xml'),
        name='lti_config_view'),
    url(r'^redirect',
        ReturnRedirectView.as_view(),
        name='redirect_view')
]


text:
title:  Prihovárať sa za milosť
date:  29/08/2022
---

>

> 9Potom Hospodin povedal Mojžišovi: "Videl som tento ľud; je to tvrdošijný ľud. 10Teraz ma už nechaj, nech proti nim vzplanie môj hnev a vyhubím ich. Z teba však urobím veľký národ." 11Mojžiš sa však usiloval obmäkčiť Hospodina, svojho Boha, a povedal: "Hospodin, prečo planie tvoj hnev proti tvojmu ľudu, ktorý si svojou veľkou silou a mocnou rukou vyviedol z Egypta? 12Prečo majú Egypťania hovoriť: 'Zlomyseľne ich vyviedol, aby ich vyvraždil na vrchoch a zmietol z povrchu zeme?' Odvráť svoj prudký hnev, upusť od zlého úmyslu proti svojmu ľudu. 13Rozpomeň sa na Abraháma, Izáka a Izraela, svojich služobníkov, ktorým si prisahal sám na seba a ktorým si prisľúbil: 'Rozmnožím vaše potomstvo ako hviezdy na nebi a celú túto krajinu, o ktorej som vám hovoril, dám vášmu potomstvu, aby ju navždy vlastnilo.'" 14Hospodin sa zľutoval a upustil od zla, ktoré ohlásil svojmu ľudu. (2Moj 32,9–14)

**Osobné štúdium**

`Prečítaj si text 2Moj 32,1–14. Sústreď sa na Mojžišovo konanie a uvažuj o jeho motivácii. Odkiaľ bral inšpiráciu zastať sa ľudu?`

Keď ľudia začali uctievať zlaté teľa, Boh rozhodol, že zašli priďaleko, že ich zničí a z Mojžiša urobí veľký národ. Mojžiš však túto ponuku neprijal. Prosil Hospodina, aby ľudu preukázal milosť. A Boh sa nad ľudom zmiloval.

Mojžiš mohol prijať Božie rozhodnutie a dovoliť, aby sa z neho stal veľký národ. Vidíme, že Boží návrh zničiť tvrdohlavý národ a požehnať Mojžiša sa stal pre Mojžiša skúškou. Mojžišova reakcia odhaľuje, koľko zľutovania a súcitu má Mojžiš so vzdorovitým ľudom. Vidíme, že Mojžiš v tejto skúške obstál. Podobne ako Ježiš, aj on prosil o milosť pre hriešnikov. Čo z toho vyplýva? Boh na nás niekedy môže dopustiť skúšku, aby sme my, On i celý vesmír videli, koľko súcitu a trpezlivosti máme s tvrdohlavými a vzdorovitými ľuďmi.

`Opäť uvažuj o dôvodoch, ktoré viedli Mojžiša k "príhovornej modlitbe" za Izraelitov. Pokús sa jeho motiváciu zhrnúť vlastnými slovami.`

Náš dnešný text je svedectvom o tom, že odpor a neposlušnosť sa môžu stať výzvou na preukázanie milosti. Milosť ľudia najviac potrebujú vtedy, keď si ju najmenej zaslúžia. Práve vtedy však môže byť pre nás mimoriadne náročné milosť a odpustenie ponúknuť. Keď Mojžišova sestra Mária kritizovala svojho brata, on volal k Hospodinovi, aby ju uzdravil z malomocenstva (4Moj 12). Keď sa Boh rozhneval na Kóracha a jeho stúpencov a vážne im hrozil, že ich všetkých usmrtí, Mojžiš padol na tvár a prosil, aby to nerobil. Keď nasledujúci deň Izraeliti reptali proti Mojžišovi pre smrť vzbúrencov a Boh im znova hrozil záhubou, Mojžiš opäť padol na zem a naliehal na Árona, aby za nich bezodkladne vykonal obrad zmierenia (4Moj 16). Mojžiš vo svojej miernosti a pokore prosil o milosť pre tých, ktorí si to nezaslúžili.

**Aplikácia**

`Kto z tvojho okolia potrebuje práve teraz najviac milosti? Ako mu môžeš – v miernosti a pokore – prejaviť Božiu milosť?`

---

#### Dodatečné otázky k diskuzi

`Co si myslíš o příběhu z dnešního úvodního textu Bible? Proč?`

`Opravdu by Hospodin zničil Izraelce, kdyby se za ně Mojžíš nepřimluvil? Jak tomu rozumíš?`

`Proč tedy Mojžíš píše, že jeho řeč pohnula Hospodina k lítosti?`

`Proč Mojžíš takto "smlouvá" se Stvořitelem o milost pro lidi, se kterými měl jako jejich vůdce tolik starostí?`

`Jaký příklad si můžeme vzít z tohoto Mojžíšova chování?`


text:
<?php
session_start();
if (file_exists('../MyDBi.php')) {
    require_once '../MyDBi.php';
} else {
    require_once 'MyDBi.php';
}

$data = file_get_contents("php://input");

$decoded = json_decode($data);
if ($decoded != null) {
    if ($decoded->function == 'saveNoticia') {
        saveNoticia($decoded->noticia);

    } elseif ($decoded->function == 'updateNoticia') {
        updateNoticia($decoded->noticia);

    } elseif ($decoded->function == 'deleteNoticia') {
        deleteNoticia($decoded->noticia_id);

    } elseif ($decoded->function == 'saveComentario') {
        saveComentario($decoded->comentario);

    } elseif ($decoded->function == 'updateComentario') {
        updateComentario($decoded->comentario);

    } elseif ($decoded->function == 'deleteComentario') {

        deleteComentario($decoded->id);
    }
} else {

    $function = $_GET["function"];
    if ($function == 'getNoticias') {
        getNoticias();
    } elseif ($function == 'getComentarios') {
        getComentarios();
    }

}

function getComentarios()
{
    $db = new MysqliDb();
    $results = $db->rawQuery('SELECT noticia_comentario_id,
    noticia_id,
    titulo,
    detalles,
    parent_id,
    creador_id,
    0 creador,
    votos_up,
    votos_down,
    fecha
FROM arielces_uiglp.noticias_comentarios;
');

    foreach ($results as $key => $row) {
        $db->where('cliente_id', $row['creador_id']);
        $cliente = $db->get('cliente');
        $results[$key]['creador'] = $cliente;
    }
    echo json_encode($results);
}

function deleteComentario($comentario_id)
{

    $db = new MysqliDb();

    $db->where("noticia_comentario_id", $comentario_id);
//    $db->where("parent_id",  $comentario_id);
    $results = $db->delete('noticias_comentarios');

    echo json_encode($results);
}

function updateComentario($comentario)
{
    $db = new MysqliDb();

    $decoded = json_decode($comentario);

    $db->where('noticia_comentario_id', $decoded->noticia_comentario_id);

    $data = array("titulo" => $decoded->titulo,
        "detalles" => $decoded->detalles,
        "parent_id" => $decoded->parent_id,
        "votos_up" => 0,
        "votos_down" => 0);

    $results = $db->update('noticias_comentarios', $data);

    if (!$results) {
        echo json_encode($db->getLastError());
        return;
    }

    echo json_encode(1);
}

function saveComentario($comentario)
{
    $db = new MysqliDb();

    $decoded = json_decode($comentario);

    $data = array("noticia_id" => $decoded->noticia_id,
        "titulo" => $decoded->titulo,
        "detalles" => $decoded->detalles,
        "parent_id" => $decoded->parent_id,
        "creador_id" => $decoded->creador_id,
        "votos_up" => 0,
        "votos_down" => 0);

    $results = $db->insert('noticias_comentarios', $data);

    if ($results < 0) {
        echo json_encode($db->getLastError());
        return;
    }

    echo json_encode($results);

}

function deleteNoticia($noticia_id)
{

    $db = new MysqliDb();

    $results = $db->delete('noticias_fotos');
    $db->where("noticia_id", $noticia_id);

    $results = $db->delete('noticias_fotos');
    $db->where("noticia_id", $noticia_id);

    $results = $db->delete('noticias_comentarios');
    $db->where("noticia_id", $noticia_id);

    echo json_encode(1);
}

function updateNoticia($noticia)
{
    $db = new MysqliDb();

    $decoded = json_decode($noticia);

    $db->where("noticia_id", $decoded->noticia_id);

    $data = array("titulo" => $decoded->titulo,
        "detalles" => $decoded->detalles,
        "creador_id" => $decoded->creador_id,
        "vistas" => 0,
        "tipo" => $decoded->tipo,
        "fecha" => substr($decoded->fecha, 0, 10));

    $results = $db->update('noticias', $data);

    if (!$results) {
        echo json_encode($db->getLastError());
        return;
    }

    $db->where("noticia_id", $decoded->noticia_id);
    $results = $db->delete('noticias_fotos');

    $db->where("noticia_id", $decoded->noticia_id);
    $results = $db->delete('noticias_comentarios');

    $db = new MysqliDb();
    foreach ($decoded->fotos as $row) {
        $data = array("noticia_id" => $decoded->noticia_id,
            "foto" => $row->foto,
            "main" => $row->main);

        $results = $db->insert('noticias_fotos', $data);

        if ($results < 0) {
            echo json_encode($db->getLastError());
            return;
        }
    }

    foreach ($decoded->comentarios as $row) {
        $data = array("noticia_id" => $decoded->noticia_id,
            "titulo" => $row->titulo,
            "detalles" => $row->detalles,
            "parent_id" => $row->parent_id,
            "votos_up" => $row->votos_up,
            "votos_down" => $row->votos_down,
            "fecha" => $decoded->fecha);

        $results = $db->insert('noticias_comentarios', $data);

        if ($results < 0) {
            echo json_encode($db->getLastError());
            return;
        }
    }

    echo json_encode(1);
}

function saveNoticia($noticia)
{
    $db = new MysqliDb();

    $decoded = json_decode($noticia);

    $data = array("titulo" => $decoded->titulo,
        "detalles" => $decoded->detalles,
        "creador_id" => $decoded->creador_id,
        "vistas" => 0,
        "tipo" => $decoded->tipo,
        "fecha" => $decoded->fecha);

    $results = $db->insert('noticias', $data);

    if ($results < 0) {
        echo json_encode($db->getLastError());
        return;
    }

    foreach ($decoded->fotos as $row) {
        $data = array("noticia_id" => $results,
            "foto" => $row->foto,
            "main" => $row->main);

        $results = $db->insert('noticias_fotos', $data);

        if ($results < 0) {
            echo json_encode($db->getLastError());
            return;
        }
    }

    echo json_encode(1);
}

function getNoticias()
{
    $db = new MysqliDb();
    $results = $db->rawQuery('Select noticia_id, titulo, detalles, fecha, creador_id, vistas, tipo, 0 fotos, 0 comentarios from noticias order by noticia_id desc;');

    foreach ($results as $key => $row) {
        $db->where('noticia_id', $row["noticia_id"]);
        $fotos = $db->get('noticias_fotos');
        $results[$key]["fotos"] = $fotos;

        $sql_comment = 'SELECT noticia_comentario_id, noticia_id,titulo,detalles,parent_id,creador_id,0 creador,votos_up,votos_down,fecha FROM noticias_comentarios WHERE noticia_id = ' . $row["noticia_id"] . ';';
        $comentarios = $db->rawQuery($sql_comment);

        foreach ($comentarios as $keyComment => $rowComment) {
            $db2 = new MysqliDb();
            $db2->where('cliente_id', $rowComment['creador_id']);
            $cliente = $db2->get('clientes');
            $comentarios[$keyComment]['creador'] = $cliente;
        }
        $results[$key]["comentarios"] = $comentarios;

    }

    echo json_encode($results);
}


text:
`GET` {{ book.apiBaseUrl }}/api/user/access_tokens

### [headers](../request/headers.html)

### [cookies](../request/cookies.html)

### [response body](../response.html)

key name | value type
--- | ---
accessTokens | [AccessToken](../access token.html)[]


text:
FunctionalTesting = function (title) {
	this.testsCompleted = 0;
	this.successfulTests = 0;
	this.failedTests = 0;
	this.testsEl = this.createHTML(this.testsContainer);
	this.el = this.createHTML(this.container);
	this.el.appendChild(this.testsEl);
	this.headerEl = this.el.querySelector('.header');
	this.headerEl.querySelector('.title').textContent = title;
	this.completedEl = this.headerEl.querySelector('.completed');
	this.failedEl = this.headerEl.querySelector('.failed');
	this.succeededEl = this.headerEl.querySelector('.succeeded');
	this.progressBubbles = new ProgressBubbles(this.totalTests);
	this.headerEl.querySelector('.right').appendChild(this.progressBubbles.el);
	this.testClassCompleted = this.testClassCompleted.bind(this);

}

FunctionalTesting.prototype = {

	container: 	'
' +
								'
' +
									'
' +
										'

' +
										'

' +
										'
' +
											'' +
										'
' +
									'
' +
									'

' +
								'
' +
							'
',

	testsContainer: 	'

',

	passedClassName: 'passed',

	failedClassName: 'failed',

	totalTests: 0,

	testingClasses: [],

	load: function (testingClass) {
		this.testingClasses.push(testingClass);
		this.totalTests += testingClass.getTestCount();
		this.testsEl.appendChild(testingClass.el);
		this.updateUI();
		this.progressBubbles.updateTestCount(this.totalTests);
	},

	execute: function () {
		this.index = -1;
		this.headerEl.querySelector('.right').classList.remove('hidden');
		this.headerEl.querySelector('.loader').classList.add('hidden');
		this.next();
	},

	next: function () {
		this.index++;
		if(this.testingClasses[this.index]){
			this.testingClasses[this.index].execute(this);
		}
	},

	testCompleted: function (success) {
		this.testsCompleted++;
		if(success){
			this.successfulTests++;
		} else {
			this.failedTests++;
		}
		this.progressBubbles.addData(success);
		this.updateUI();
	},

	testClassCompleted: function () {
		this.next();
	},

	updateUI: function () {
		this.completedEl.textContent = 'Total Tests: ' + this.testsCompleted + '/' + this.totalTests;
		this.failedEl.textContent = 'Failed: ' + this.failedTests;
		this.succeededEl.textContent = 'Succeeded: ' + this.successfulTests;
		if (this.failedTests) {
			this.el.classList.add('failed');
			document.head.querySelector('title').textContent = 'FAILURE';
		} else if (this.totalTests == this.successfulTests){
			this.el.classList.add('success');
			document.head.querySelector('title').textContent = 'Success';
		}
	},

	createHTML: function (html) {
		var div = document.createElement('div');
		div.innerHTML = html;
		return div.children[0];
	}
}


text:
package org.wso2.carbon.identity.user.endpoint.dto;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModelProperty;

import javax.validation.Valid;

/**
 * DTO which holds the attributes of the response for successful user self-registration via external channel.
 */
public class SuccessfulUserCreationExternalResponseDTO extends SuccessfulUserCreationDTO {

    @Valid
    private String confirmationCode = null;

    /**
     * Confirmation code to verify the user, when notifications are externally managed. In this scenario,
     * *notificationChannel* will be *EXTERNAL*. Use the confirmation code for confirm the user account.
     **/
    @ApiModelProperty(value = "Confirmation code to verify the user, when notifications are externally managed. " +
            "In this scenario, *notificationChannel* will be *EXTERNAL*. Use the confirmation code for confirm the " +
            "user account.")
    @JsonProperty("confirmationCode")
    public String getConfirmationCode() {

        return confirmationCode;
    }

    /**
     * Set the confirmation code to confirm the self registration flow externally.
     *
     * @param confirmationCode Confirmation code
     */
    public void setConfirmationCode(String confirmationCode) {

        this.confirmationCode = confirmationCode;
    }
}


text:
module RDFVocabularies
  class BIBO < RDF::Vocabulary("http://purl.org/ontology/bibo/")
    term :Book
    term :Document

    property :isbn10
    property :isbn13
    property :oclcnum
  end
end


text:
import argparse

# Github Access, , access repositories on github, internal
from .lib import github_access
# Registry Access, , access modules in the registry, internal
from .lib import registry_access

def addOptions(parser):
    # set the registry URL to save an API key for
    parser.add_argument('--registry', dest='registry', help=argparse.SUPPRESS)
    # pass the API key for logging into this registry (it will be saved, and
    # used for future requests to this registry)
    parser.add_argument('--apikey', '-k', dest='apikey', help=argparse.SUPPRESS)

def execCommand(args, following_args):
    if args.apikey:
        registry_access.setAPIKey(args.registry, args.apikey)

    github_access.authorizeUser(args.registry, provider=None)


text:
Use the Whois integration to get enriched data for domains and ips.

### Configuration Options
- **Return Errors**: If selected, Whois will return errors for unsupported domains, or domains for which the lookup failed.

**For the domain and whois commands:**
- **Proxy URL**: Specify a proxy to be used. The URL should in the format: scheme://host:port. If the scheme is omitted, the default socks5h scheme will be used. To use the system HTTP proxy, you can also specify the value: **system_http** or sign the **Use system proxy settings**. The following schemes are supported:
  * **socks5h**: SOCKS version 5 protocol with remote DNS resolving.
  * **socks5**: SOCKS version 5 protocol with local DNS resolving.
  * **socks4a**: SOCKS version 4 with remote DNS resolving.
  * **socks4**: SOCKS version 4 with local DNS resolving.
  * **http**: HTTP proxy with support for CONNECT method on port 43 (default Whois port). Note that most HTTP proxies block the CONNECT method to non-HTTP/HTTPS standard ports (such as the default Whois port 43).

**For the IP command:**
- **Use system proxy settings**: Use the system proxy settings for the `ip` command.


text:
/*!
 *
 * @file virtual_camera.h
 *
 * @author
 *
 * @version
 *
 * @date Jul-20-2010
 *
 * @brief The file contains Macro's and functions required for Virtual Camera
 *        Loopback Application
 *
 *****************************************************************************/

#ifndef _WRITE_SD_DATA_H
#define _WRITE_SD_DATA_H

#include "types.h"
#include "user_config.h"

/******************************************************************************
 * Constants - None
 *****************************************************************************/

/******************************************************************************
 * Macro's
 *****************************************************************************/
#define USB_CONTROLLER_ID       (0)

    #define LENGTH_OF_EACH_LAB              (512)
                                            /* length of each logical address block */
    #define TOTAL_LOGICAL_ADDRESS_BLOCKS    (0x010000)
                                            /* total number of logical blocks present */
    #define DISK_SIZE                       (LENGTH_OF_EACH_LAB * TOTAL_LOGICAL_ADDRESS_BLOCKS)
#define LOGICAL_UNIT_SUPPORTED              (1)
#define BUFER_SIZE BLOCK_SIZE

#pragma pack(1)

typedef struct _disk_variable_struct
{
    uint_8 app_controller_ID;
    boolean start_app;
    /* disk space reserved */
    uint_8 storage_disk[10];
    uint_8 disk_lock;
}DISK_GLOBAL_VARIABLE_STRUCT, *PTR_DISK_GLOBAL_VARIABLE_STRUCT;

#define  FLASH_IMAGE_SUCCESS    0
#define  FLASH_IMAGE_ERROR      1

/* Bootloader Status */
#define BootloaderReady         0
#define BootloaderS19Error      1
#define BootloaderFlashError    2
#define BootloaderSuccess       3
#define BootloaderStarted       4

/*****************************************************************************
 * Global variables
 *****************************************************************************/

/*****************************************************************************
 * Global Functions
 *****************************************************************************/
void Disk_App(void);
void USB_MSD_App_Callback(uint_8 controller_ID,uint_8 event_type,void* val);
void MSD_Event_Callback(uint_8 controller_ID,uint_8 event_type,void* val);

#endif


text:
<?php

namespace Iphp\FileStoreBundle\Tests;

use Doctrine\ORM\Proxy\Proxy;

/**
 * DummyEntityProxyORM.
 *
 * @author Vitiko <vitiko@mail.ru>
 */
class DummyEntityProxyORM extends DummyEntity implements Proxy
{
    public function __load() { }

    public function __isInitialized() { }
}


text:
every :reboot do
  rake "xapian_db:reindex"
end

# Example:
#
# set :output, "/path/to/my/cron_log.log"
#
# every 2.hours do
#   command "/usr/bin/some_great_command"
#   runner "MyModel.some_method"
#   rake "some:great:rake:task"
# end
#
# every 4.days do
#   runner "AnotherModel.prune_old_records"
# end
#
# every :reboot do
# every :friday, :at => '3:30 am' do
# Learn more: http://github.com/javan/whenever


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lich. -Fl. Great Brit. 236 (1871)

#### Original name
Lichen westringii Lilj.

### Remarks
null


text:
/**
 * Created by adm on 05.11.15.
 */
module UserInterfaceModule{
    export class hud {

        game;
        uiBackground:Phaser.Group;

        constructor(){
            this.game = GraphicsModule.GraphicsManager.getInstance().game;
            this.uiBackground();
        }

        uiBackground(){
            var lifeBackground:Phaser.Sprite = new Phaser.Sprite(this.game, 0,0, "ui", "life_frame.png")
            var enemyLifeBackground:Phaser.Sprite = new Phaser.Sprite(this.game, 1308,0, "ui", "life_frame.png")
            enemyLifeBackground.width = -enemyLifeBackground.width;

            this.uiBackground = new Phaser.Group(this.game);

            this.uiBackground.add(lifeBackground);
            this.uiBackground.add(enemyLifeBackground);

            this.uiBackground.fixedToCamera = true;
        }
    }
}


text:
import angular from 'angular';
import likeHeartTemplate from './like-heart.ng.html';
import buttonTemplate from './like-heart-button.ng.html';

function LikeHeartCtrl($scope, $mdToast, $reactive) {
  'ngInject';

  $reactive(this).attach($scope);

  const vm = this;

  vm.likesTarget = likesTarget;

  vm.toggleLike = toggleLike;

  function toggleLike() {
    let like;
    if (Meteor.userId() == null) {
      $mdToast.show($mdToast.simple().content('Please login to like this').position('bottom right').hideDelay(4000));
      return;
    }
    like = Likes.findOne({
      liker: Meteor.userId(),
      likee: vm.targetId,
    });
    if (like != null) {
      Likes.remove(like._id);
      if (vm.unlikeText) {
        $mdToast.show($mdToast.simple().content(vm.unlikeText).position('bottom right').hideDelay(4000));
      }
    } else {
      vm.call('/likes/add', vm.targetId, vm.category, (err, response) => {
        if (err) {
          return console.log(err);
        } else if (vm.likeText) {
          $mdToast.show($mdToast.simple().content(vm.likeText).position('bottom right').hideDelay(4000));
        }
      });
    }
  }

  function likesTarget() {
    let like;
    like = Likes.findOne({
      liker: Meteor.userId(),
      likee: vm.targetId,
    });
    if (like) {
      return 'liked';
    }
    return 'not-liked';
  }
}

angular.module('food-coop').component('likeHeart', {
  template: likeHeartTemplate,
  controller: LikeHeartCtrl,
  bindings: {
    likeText: '@',
    unlikeText: '@',
    targetId: '<',
    category: '@',
  },
});

angular.module('food-coop').component('likeHeartButton', {
  template: buttonTemplate,
  controller: LikeHeartCtrl,
  bindings: {
    likeText: '@',
    unlikeText: '@',
    targetId: '<',
    category: '@',
  },
});


text:
CREATE DATABASE jitty;
CREATE USER 'jitty'@'localhost'
  IDENTIFIED BY 'jitty';
GRANT ALL ON jitty.* TO 'jitty'@'localhost';


text:
import os
from Omnipresent import len_
from Downloader.VisualizeHistory import loadHistory
from ResultsGraphing.custom import finally_show, plot_2x2_detailed, count_averages, save_plot, boxplots_in_row,boxplots_in_row_custom611

dir_folder = os.path.dirname(os.path.abspath(__file__))

###
"""
The idea:
    Demonstrate effectivity of spliting long edges.
    We have datasets:
        original 5556x_markable_640x640
        minlen10 5556x_minlen10_640px
        minlen20 5556x_minlen20_640px
        minlen30 5556x_minlen30_640px
    with both mixed and image model.

    Lets start with mixed model. In total we want to produce 3 figures.
    First is showing validation error in the last epoch of these 4 datasets via box plots.
    Alternatively it can show both the validation and training error.
    Four plot boxes next to each other.

    Second is showing averages of the validation error only. All four datasets
    are in the same image - we show only the average in hope that its more clear.
    One shared graph plot.

    Third is a information overload kind of graph,
    we want to draw grid of 2x2 with all four datasets, each having a graph plot with
    both training and validation error over the evolution of epochs.

"""

SAVE = True
model_txt = "mix" # or img

path_folder = dir_folder + '/data/k-fold-tests/6.1.2. splitting long edges - minlen/'
out_folder = dir_folder + '/graphs/6.1.2._splitting_long_edges-minlen/fig1_boxplot_best_'+model_txt

if model_txt == "mix":
    original = path_folder + "mix_original_1760999.npy"
    minlen10 = path_folder + "mix_minlen10.npy"
    minlen20 = path_folder + "mix_minlen20.npy"
    minlen30 = path_folder + "mix_minlen30_1761323.npy"
else:
    original = path_folder + "img_original_1769351.npy"
    minlen10 = path_folder + "img_minlen10_1771003.npy"
    minlen20 = path_folder + "img_minlen20.npy"
    minlen30 = path_folder + "img_minlen30_1769353.npy"

data_paths = [original, minlen10, minlen20, minlen30]
val_data_names = [
    "original",
    "minlen10",
    "minlen20",
    "minlen30"]
train_data_names = [
    "original",
    "minlen10",
    "minlen20",
    "minlen30"]
hard_colors = ['red', 'green', 'blue', 'orange']
light_colors = ['pink', 'lightgreen', 'lightblue', 'yellow']
both_colors = []
both_data_names = []

special_histories = []
for i in range(0,len(data_paths)):
    special_histories.append(loadHistory(data_paths[i]))
    special_histories[i] = count_averages(special_histories[i], 'loss')

    both_colors.append(light_colors[i])
    both_colors.append(hard_colors[i])
    both_data_names.append(train_data_names[i])
    both_data_names.append("validation "+val_data_names[i])

custom_title = 'Validation error in last epoch'

import matplotlib.pyplot as plt
BestInstead = True
Notch = False

plt, figure = boxplots_in_row(plt, special_histories, val_data_names, BestInstead=BestInstead, Notch=Notch)
#plt, figure = boxplots_in_row_custom611(plt, special_histories, val_data_names, BestInstead=BestInstead, just='both')

figure.set_size_inches( (8, 6) )

# Now check everything with the defaults:
DPI = figure.get_dpi()
print "DPI:", DPI
DefaultSize = figure.get_size_inches()
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])

save_plot(plt, SAVE, out_folder)

finally_show(plt)


text:
package com.hpe.caf.worker.example;

import com.hpe.caf.api.worker.WorkerConfiguration;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * Configuration for the ExampleWorker, read in from test-configs/cfg_test_worker-example-ExampleWorkerConfiguration.
 */
public class ExampleWorkerConfiguration extends WorkerConfiguration {

    /**
     * Output queue to return results to RabbitMQ.
     */
    @NotNull
    @Size(min = 1)
    private String outputQueue;

    /**
     * Number of threads to use in the worker.
     */
    @Min(1)
    @Max(20)
    private int threads;

    /**
     * The size, in bytes, at which to write results to the DataStore instead of keeping them just in memory.
     */
    @Min(1024)
    @Max(100 * 1024)
    private int resultSizeThreshold;

    public ExampleWorkerConfiguration() { }

    public String getOutputQueue() {
        return outputQueue;
    }

    public void setOutputQueue(String outputQueue) {
        this.outputQueue = outputQueue;
    }

    public int getThreads() {
        return threads;
    }

    public void setThreads(int threads) {
        this.threads = threads;
    }

    public int getResultSizeThreshold() {
        return resultSizeThreshold;
    }

    public void setResultSizeThreshold(int resultSizeThreshold) {
        this.resultSizeThreshold = resultSizeThreshold;
    }
}


text:
#include "unicode/parsepos.h"

U_NAMESPACE_BEGIN

UOBJECT_DEFINE_RTTI_IMPLEMENTATION(ParsePosition)

ParsePosition::~ParsePosition() {}

ParsePosition *
ParsePosition::clone() const {
    return new ParsePosition(*this);
}

U_NAMESPACE_END


text:
#include "Sound.h"

class SoundCache: boost::noncopyable
{
public:
  Sound &Get( const char *szFile );
  const Sound &Get( const char *szFile ) const;

private:
  typedef std::map< std::string, Sound::TPtr > TSounds;

private:
  TSounds m_sounds;
};

#endif // SoundCache_h__


text:
`extends japidviews._layouts.Layout` `set title:"Login Page"`

		$flash.get("msg")

	<form action="/login" id="form2" method="post">

			User Name <input id="username" name="username" type="text" value="$flash(" username")" placeholder="User Name" />

			Password <input id="password" name="password" type="text" placeholder="Password" />

			<input id="remember" name="remember" type="checkbox" value="1" placeholder="Remember" />   Is remember?

			<input type="submit" value="Login" class="btn" />

	</form>


text:
package org.onosproject.vtnrsc.util;

import org.onosproject.store.service.Topic;
import org.onosproject.store.service.ConsistentTreeMapBuilder;
import org.onosproject.store.service.WorkQueue;
import org.onosproject.store.service.EventuallyConsistentMapBuilder;
import org.onosproject.store.service.ConsistentMapBuilder;
import org.onosproject.store.service.DistributedSetBuilder;
import org.onosproject.store.service.AtomicCounterBuilder;
import org.onosproject.store.service.AtomicValueBuilder;
import org.onosproject.store.service.LeaderElectorBuilder;
import org.onosproject.store.service.Serializer;
import org.onosproject.store.service.TransactionContextBuilder;
import org.onosproject.store.service.StorageService;

/**
 * Adapter for the storage service.
 */
public class VtnStorageServiceAdapter implements StorageService {
    @Override
    public <K, V> EventuallyConsistentMapBuilder<K, V> eventuallyConsistentMapBuilder() {
        return null;
    }

    @Override
    public <K, V> ConsistentMapBuilder<K, V> consistentMapBuilder() {
        return null;
    }

    @Override
    public <V> ConsistentTreeMapBuilder<V> consistentTreeMapBuilder() {
        return null;
    }

    @Override
    public <E> DistributedSetBuilder<E> setBuilder() {
        return null;
    }

    @Override
    public AtomicCounterBuilder atomicCounterBuilder() {
        return null;
    }

    @Override
    public <V> AtomicValueBuilder<V> atomicValueBuilder() {
        return null;
    }

    @Override
    public TransactionContextBuilder transactionContextBuilder() {
        return null;
    }

    @Override
    public LeaderElectorBuilder leaderElectorBuilder() {
        return null;
    }

    @Override
    public <E> WorkQueue<E> getWorkQueue(String name, Serializer serializer) {
        return null;
    }

    @Override
    public <T> Topic<T> getTopic(String name, Serializer serializer) {
        return null;
    }
}


text:
angular.module('ui.bootstrap.demo').controller('DropdownCtrl', function ($scope, $log) {
  $scope.items = [
    'The first choice!',
    'And another choice for you.',
    'but wait! A third!'
  ];

  $scope.status = {
    isopen: false
  };

  $scope.toggled = function(open) {
    $log.log('Dropdown is now: ', open);
  };

  $scope.toggleDropdown = function($event) {
    $event.preventDefault();
    $event.stopPropagation();
    $scope.status.isopen = !$scope.status.isopen;
  };
});


text:
var DSON = require('../core');

DSON.register('$array', Array, function(arr) {
	return arr.slice();
}, function(value) {
	return value;
}, {
	collapse: true
});


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/insert_image"
        android:icon="@drawable/ic_insert_image"
        app:showAsAction="always"
        android:title="insert image"/>

    <item
        android:id="@+id/post"
        android:icon="@drawable/ic_post"
        app:showAsAction="always"
        android:title="post"/>

</menu>


text:
    <template>

            <spinner :loading="loading" :text='loadingText'/>

Error: user must be logged in to access this page.

            <md-card style="margin: 10px" >
                <form class="modal-content" action="" method="post"
                  enctype="multipart/form-data"
                  upload_type="http://www.w3.org/ns/dcat#Dataset">
                <md-steppers :md-active-step.sync="active" md-linear>

                  <md-step id="first" md-label="Upload files" :md-done.sync="first">

                      <md-field style="max-width: 100%;">
                        DOI of related publication (e.g., 10.1000/000)
                        <md-input v-model="doi"></md-input>
                      </md-field>

                        <md-field style="max-width: none;" :class="{ 'md-invalid': isInvalidUpload }">
                          Select files to upload for this dataset
                          <md-file v-model="distr_upload" id="distrFiles" multiple required isInvalidValue=false
                            v-on:change="handleDistrUpload($event.target.files)"/>
                          Error in upload. Please try again
                          At least one distribution is required
                        </md-field>

{{ file.name }}

                                <md-field style="max-width: 90%;">
                                  Label
                                  <md-input v-model=file.label></md-input>
                                  <md-tooltip md-delay="300">Provide a human-readable label or leave as the default</md-tooltip>
                                </md-field>

                                <md-button class="remove-file md-raised" v-on:click="removeFile( key )">Remove file</md-button>

                        <md-field style="max-width: none;">
                          Select a representative image to use as thumbnail
                          <md-file
                            id="repImgUploader" v-model="rep_image" accept="image/*"
                            v-on:change="handleImgUpload($event.target.files); previewFile()"/>
                          Error in upload. Please try again
                        </md-field>

{{ dataset.depiction.name }}

                          <md-button style="margin-left: 40px;" type="button" class="close md-raised" @click="removeImage()">Remove image</md-button>

                          <md-button
                            class="md-raised md-primary"
                            @click="checkFirstPage()">
                            Upload and continue
                          </md-button>

                          <md-progress-spinner :md-diameter="30" :md-stroke="3" md-mode="indeterminate"></md-progress-spinner>

                    </md-step>

                    <md-step id="second" md-label="Provide additional info" :md-done.sync="second">

                        <md-content style="width: 100%; margin: 20px">

                            General Information

                          <md-field style="max-width: 100%;" :class="{ 'md-invalid': (isInvalidForm && (dataset.title === ''))}">
                            Title
                            <md-input v-model="dataset.title" required></md-input>
                            Title required
                          </md-field>

Contact Point

                              <md-field :class="{ 'md-invalid': (isInvalidForm && ((cpID === null) || (cpID==='')) )}" style="max-width: 100%;">
                                ORCID Identifier (e.g., 0000-0001-2345-6789)
                                <md-input v-model="cpID" required v-on:change="lookupOrcid()"></md-input>
                                ORCID iD required
                              </md-field>

                              <md-field :class="{ 'md-invalid': (isInvalidForm && (dataset.contactpoint.cpfirstname === ''))}">
                                First name
                                <md-input v-model="dataset.contactpoint.cpfirstname" required></md-input>
                                Contact point required
                              </md-field>

                              <md-field :class="{ 'md-invalid': (isInvalidForm && (dataset.contactpoint.cplastname === ''))}">
                                Last name
                                <md-input v-model="dataset.contactpoint.cplastname" required></md-input>
                                Contact point required
                              </md-field>

                              <md-field :class="{ 'md-invalid': (isInvalidForm && (dataset.contactpoint.cpemail === ''))}" style="max-width: 100%;">
                                Email
                                <md-input v-model="dataset.contactpoint.cpemail" required></md-input>
                                Valid email required
                              </md-field>

                            No results found for {{cpID}}

                            Don't have an ORCID iD?
                            Create one here

                          <md-field style="max-width: 100%;" :class="{ 'md-invalid': (isInvalidForm && (dataset.description === ''))}">
                            Text Description
                            <md-textarea v-model="dataset.description" required></md-textarea>
                            Description required
                          </md-field>

                        </md-content>

                        <md-divider style="border-style: solid" width="100%"></md-divider>

                        <md-content style="width: 100%; margin: 20px">

                            Contributors

                            <md-autocomplete
                              style="min-width: 100%;"
                              v-model="selectedAuthor"
                              :md-options="autocomplete.availableAuthors"
                              :md-open-on-focus="false"
                              @md-changed="resolveEntityAuthor"
                              @md-selected="selectedAuthorChange"
                              @md-opened="setListStyle"
                              @md-closed="setListStyle(true)"
                            >
                              Search for Author

                              <template style="width: 90% !important; left: 1px !important;" slot="md-autocomplete-item" slot-scope="{ item, term }">
                                {{item.label}}
                              </template>

                              <template style="width: 90% !important; left: 1px !important" slot="md-autocomplete-empty" slot-scope="{ term }">

No authors matching "{{ term }}" were found.

                                Create new
                              </template>
                            </md-autocomplete>

                                    {{contributors[index]['name']}}

                                    <md-autocomplete
                                      style="max-width: 90%;"
                                      v-model="row['onbehalfof']['name']"
                                      :md-options="autocomplete.availableInstitutions"
                                      :md-open-on-focus="false"
                                      @md-changed="resolveEntityInstitution"
                                      @md-selected="selectedOrgChange(index, $event)"
                                    >
                                      Organization

                                      <template style="max-width: 90%;" slot="md-autocomplete-item" slot-scope="{ item, term }">
                                        <md-highlight-text :md-term="term">{{ item.label }}</md-highlight-text>
                                      </template>

                                      <template style="max-width: 90%;" slot="md-autocomplete-empty" slot-scope="{ term }">

No organizations matching "{{ term }}" were found.

                                        Create new
                                      </template>
                                    </md-autocomplete>

                                    Remove

                        </md-content>

                        <md-divider style="border-style: solid" width="100%"></md-divider>

                        <md-content style="width: 100%; margin: 20px">

                            Publication Information

                                Date Published
                                <md-field>
                                  <md-input v-model="dataset.datepub['@value']" type="date"
                                  :formatter="dateFormat"></md-input>
                                </md-field>

                                Date Last Modified
                                <md-field>
                                  <md-input v-model="dataset.datemod['@value']" type="date"
                                  :formatter="dateFormat"></md-input>
                                </md-field>

                        </md-content>
                        <md-button class="md-raised md-primary" @click="checkSecondPage">Next</md-button>
                        Check for errors in required fields

                    </md-step>

                    <md-step id="third" md-label="Confirm and Submit" :md-done.sync="third">

                        Form Results

                      <md-content style="width: 100%; margin: 20px">
                        Title: {{ dataset.title }}

                          Contact Point: {{ dataset.contactpoint.cpfirstname }}
                          {{ dataset.contactpoint.cplastname }} -
                          {{ dataset.contactpoint.cpemail }}

Text Description: {{ dataset.description }}

                        Contributors

                          {{elem.name}}
                          <template v-if="(elem.onbehalfof !== null)&&(elem.onbehalfof.name !== undefined)"> - {{elem.onbehalfof.name}}</template>

Date Published: {{ dataset.datepub['@value'] }}

Date Last Modified: {{ dataset.datemod['@value'] }}

 Related publication:

                          {{ dataset.refby }}

Distribution(s):

                          {{ file.name }}

Representative Image: {{ rep_image }}

                      </md-content>

                      <md-card-actions>
                        <md-button v-on:click="submitForm" class="md-primary"
                          >Submit</md-button
                        >
                      </md-card-actions>

                    </md-step>
                </md-steppers>
                </form>
              </md-card>

      </template>


text:
<?php

namespace Shivoham\ValueObjectFormBundle\Form\Extension;

use Symfony\Component\Form\DataMapperInterface;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\Extension\Core\DataMapper\PropertyPathMapper;

class FormExtension extends AbstractTypeExtension implements DataMapperInterface
{
    private $propertyAccessor;

    private $propertyPathMapper;

    public function __construct(PropertyAccessorInterface $propertyAccessor = null)
    {
        $this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
        $this->propertyPathMapper = new PropertyPathMapper($this->propertyAccessor);
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        if (!isset($options['object_accessor']) || !isset($options['object_mutator'])) {
            return;
        }

        $builder->setDataMapper($this);
    }

    public function mapDataToForms($data, $forms)
    {
        $forms = iterator_to_array($forms);
        $parent = current($forms)->getParent();
        $options = $parent->getConfig()->getOptions();

        return $this->propertyAccessor->getValue($data, $options['object_accessor']);
    }

    public function mapFormsToData($forms, &$data)
    {
        $forms = iterator_to_array($forms);
        $parent = current($forms)->getParent();
        $options = $parent->getConfig()->getOptions();

        $result = [];
        if (isset($options['value_object_class'])) {
            $valueObjectClass = $options['value_object_class'];
            $result = new $valueObjectClass();
            $this->propertyPathMapper->mapFormsToData($forms, $result);
        } else {
            foreach ($forms as $key => $form) {
                $result[$key] = $form->getData();
            }
        }

        try {
            $this->propertyAccessor->setValue($data, $options['object_mutator'], $result);
        } catch (\Symfony\Component\PropertyAccess\Exception\ExceptionInterface $e) {
            throw $e;
        } catch (\Exception $e) {
            $parent->addError(new FormError($e->getMessage()));
        }
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefined(['object_accessor', 'object_mutator', 'value_object_class']);
    }

    public function getExtendedType()
    {
        return FormType::class;
    }
}


text:
package Main;

import AutomatonSimulator.Automaton;
import GrammarSimulator.Grammar;
import PushDownAutomatonSimulator.PushDownAutomaton;

import java.util.HashMap;

/**
 * This class contains and manages the actual content. Stored Grammars, Automaton, ...
 * @author Isabel
 * @since 30.01.2017
 */
public class Content {

    /**
     * Contains all loaded objects (Automaton, Grammars, etc.).
     * The class-type of the object is mapped to an instance of it.
     */
    private final HashMap<Class, Storable> objects = new HashMap<>();

    /**
     * Contains all stored (saved) objects (Automaton, Grammars, etc.).
     * The class-type of the object is mapped to a hashmap.
     * In this map names are mapped to instances of the class
     */
    private final HashMap<Class, HashMap<String, Storable>> store= new HashMap<>();

    /**
     * Contains the different types of storable objects (Automaton, Grammar, etc.).
     * Maps the name of the class to the class.
     * If you want to add new types of storable objects to the application, you need
     * to add an entry to this hashmap.
     */
    private final HashMap<String,Class> lookUpTable =new HashMap<>();

    Content() {
       init();

    }

    void init() {
        lookUpTable.put("grammar", Grammar.class);
        lookUpTable.put("automaton", Automaton.class);
        lookUpTable.put("pda", PushDownAutomaton.class);
        lookUpTable.put("pushdownautomaton",PushDownAutomaton.class);

        lookUpTable.values().forEach(clazz -> store.putIfAbsent(clazz, new HashMap<>()));
    }

    /**
     * Getter-Method for {@link #lookUpTable}
     * @return the {@link #lookUpTable}
     */
    public HashMap<String, Class> getLookUpTable() {
        return lookUpTable;
    }

    /**
     * Getter-Method for {@link #objects}
     * @return the {@link #objects}
     */
    public HashMap<Class, Storable> getObjects() {
        return objects;
    }

    /**
     * Getter-Method for {@link #store}
     * @return the {@link #store}
     */
    public HashMap<Class, HashMap<String, Storable>> getStore() {
        return store;
    }
}


text:
package com.actionml.admin

import cats.data.Validated
import com.actionml.core.engine.Engine
import com.actionml.core.model.Response
import com.actionml.core.validate.ValidateError
import com.typesafe.config.{Config, ConfigFactory}
import com.typesafe.scalalogging.LazyLogging

import scala.concurrent.{ExecutionContext, Future}

/** Handles commands or Rest requests that are system-wide, not the concern of a single Engine */
abstract class Administrator extends LazyLogging {

  lazy val config: Config = ConfigFactory.load()

  // engine management
  def getEngine(engineId: String): Option[Engine]
  def addEngine(json: String): Validated[ValidateError, Response]
  def removeEngine(engineId: String): Validated[ValidateError, Response]
  def updateEngine(json: String): Validated[ValidateError, Response]
  def updateEngineWithTrain(engineId: String): Validated[ValidateError, Response]
  def updateEngineWithImport(engineId: String, inputPath: String): Validated[ValidateError, Response]
  def status(resourceId: String): Validated[ValidateError, Response]
  def statuses(): Validated[ValidateError, List[Response]]
  def systemInfo(): Validated[ValidateError, Response]
  def init(): Administrator = this
  def cancelJob(engineId: String, jobId: String): Validated[ValidateError, Response]
  def healthCheck(implicit ec: ExecutionContext): Future[Response]
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Policy
      xmlns="urn:oasis:names:tc:xacml:2.0:policy:schema:os"
      xmlns:gml="http://www.opengis.net/gml"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="urn:oasis:names:tc:xacml:2.0:policy:schema:os http://docs.oasis-open.org/xacml/access_control-xacml-2.0-policy-schema-os.xsd" PolicyId="urn:oasis:names:tc:example:testPolicyAuthorisePermit" RuleCombiningAlgId="urn:oasis:names:tc:xacml:1.0:rule-combining-algorithm:deny-overrides">

  <!-- This Policy only applies to requests on the SampleServer -->
  <Target>
    <Resources>
    <Resource>
      <ResourceMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
        <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">SampleServer</AttributeValue>
        <ResourceAttributeDesignator DataType="http://www.w3.org/2001/XMLSchema#string"
                                     AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id"/>
       </ResourceMatch>
      </Resource>
    </Resources>
  </Target>

  <Rule RuleId="LoginRule2" Effect="Permit">

    <!-- Only use this Rule if the action is login -->
    <Target>
      <Actions>
        <Action>
          <ActionMatch MatchId="urn:oasis:names:tc:xacml:1.0:function:string-equal">
            <AttributeValue DataType="http://www.w3.org/2001/XMLSchema#string">login</AttributeValue>
            <ActionAttributeDesignator DataType="http://www.w3.org/2001/XMLSchema#string"
                                       AttributeId="ServerAction"/>
          </ActionMatch>
        </Action>
      </Actions>
    </Target>

   <Condition>
    <Apply FunctionId="urn:oasis:names:tc:xacml:1.0:function:any-of">
        <Function FunctionId="urn:ogc:def:function:geoxacml:1.0:geometry-overlaps"/>
            <AttributeValue DataType="urn:ogc:def:dataType:geoxacml:1.0:geometry">
            <Polygon gid="P2" srsName="EPSG:4326">
                 <outerBoundaryIs>
                <LinearRing>
                    <coord> <X>-200.0</X> <Y>0.0</Y>  </coord>
                    <coord> <X>-200.0</X> <Y>50.0</Y> </coord>
                    <coord> <X>200.0</X>  <Y>50.0</Y> </coord>
                 </LinearRing>
               </outerBoundaryIs>
             </Polygon>
            </AttributeValue>
           <ResourceAttributeDesignator
             DataType="urn:ogc:def:dataType:geoxacml:1.0:geometry"
             AttributeId="RequestBoundingBox" />
     </Apply>
    </Condition>

  </Rule>
</Policy>


text:
package com.ucla.nesl.lib;

import java.util.ArrayList;
import java.util.Map;

import org.json.JSONObject;

import com.ucla.nesl.aidl.Device;

public interface UniversalEventListener {
	/**
	 * Called when sensor values have changed.
	 *
See {@link android.hardware.SensorManager SensorManager}
	 * for details on possible sensor types.
	 *
See also {@link android.hardware.SensorEvent SensorEvent}.
	 *
	 *
NOTE: The application doesn't own the
	 * {@link android.hardware.SensorEvent event}
	 * object passed as a parameter and therefore cannot hold on to it.
	 * The object may be part of an internal pool and may be reused by
	 * the framework.
	 *
	 * @param event the {@link android.hardware.SensorEvent SensorEvent}.
	 */
	public void onSensorChanged(String devID, int sType, float[] values, long[] timestamp);

	public void notifySensorChanged(String devID, int sType, int action);

	void notifyNewDevice(Device mdevice);

	void listHistoricalDevices(Map<String, ArrayList<Integer>> deviceList);

	void historicalDataResponse(int txnID, String devID, int sType, int cmd, JSONObject result);

	void disconnected();

	void onUniDevConnected();
}


text:
FROM ubuntu:14.04
MAINTAINER Florian GAUVIN "florian.gauvin@nl.thalesgroup.com"

ENV DEBIAN_FRONTEND noninteractive
#ENV http_proxy=http://10.160.64.104:8080
#ENV https_proxy=http://10.160.64.104:8080

#Download all the packages needed

RUN apt-get update && apt-get install -y \
	build-essential \
        cmake \
	git \
	python \
	wget \
	unzip \
	bc\
	language-pack-en \
	curl \
	uuid-dev \
    	libjansson-dev \
    	libxml2-dev \
    	libcurl4-openssl-dev \
	mercurial \
	zip \
	openjdk-7-jdk \
	libcups2-dev \
	libfreetype6-dev \
	libasound2-dev\
	libffi-dev \
	libX11-dev \
	libxext-dev \
	libxrender-dev \
	libxtst-dev \
	libxt-dev \
        runit \
        && apt-get clean
# Update CMAKE
RUN mkdir /cmake && cd /cmake && wget http://www.cmake.org/files/v3.4/cmake-3.4.3.tar.gz && tar xf cmake-3.4.3.tar.gz && cd cmake-3.4.3 && ./configure --prefix=/usr && make && make install

# Get CppUtest
RUN mkdir /cpputest && cd  /cpputest &&  wget https://github.com/cpputest/cpputest.github.io/blob/master/releases/cpputest-3.7.1.tar.gz?raw=true -O cpputest.tgz && tar xf cpputest.tgz && cd cpputest-3.7.1 && ./configure --prefix=/usr && make && sudo make install

#Download and install the latest version of Docker (You need to be the same version to use this Dockerfile)
RUN wget -qO- https://get.docker.com/ | sh

#Prepare the usr directory by downloading in it : Buildroot, the configuration files of Buildroot, Apache Celix, Apache Felix and Apache Ace

WORKDIR /usr

RUN wget http://git.buildroot.net/buildroot/snapshot/buildroot-2016.02.tar.gz && \
	tar -xf buildroot-2016.02.tar.gz && \
        echo "HOST_FAKEROOT_CONF_OPTS += --with-ipc=tcp" >> /usr/buildroot-2016.02/package/fakeroot/fakeroot.mk && \
        echo 'source "package/etcd/Config.in"' >> /usr/buildroot-2016.02/Config.in

#Add missing packages to the buildroot environment
ADD extra_buildroot_packages/etcd /usr/buildroot-2016.02/package/etcd

#ZEROMQ 3.2.5 has to be used instead of the default 4.x
RUN sed -i -e 's/ZEROMQ_VERSION.*/ZEROMQ_VERSION = 3.2.5/' /usr/buildroot-2016.02/package/zeromq/zeromq.mk && rm -f /usr/buildroot-2016.02/package/zeromq/zeromq.hash && rm -f /usr/buildroot-2016.02/package/zeromq/*patch

#Copy the configuration file of the app-builder in Buildroot and create a small base of the future image with buildroot and decompress it
ADD buildroot-configure-app-builder/.config /usr/buildroot-2016.02/
WORKDIR /usr/buildroot-2016.02

RUN make


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE catalog PUBLIC "-//OASIS//DTD Entity Resolution XML Catalog V1.0//EN" "http://www.oasis-open.org/committees/entity/release/1.0/catalog.dtd">
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog">
</catalog>


text:
package 'libapache2-mod-jk' do
  case node['platform_family']
  when 'rhel', 'fedora'
    package_name 'mod_jk'
  when 'suse'
    package 'apache2-mod_jk'
  else
    package_name 'libapache2-mod-jk'
  end
end

apache_module 'jk'


text:
var gulp = require('gulp');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var newer = require('gulp-newer');
var critical = require('critical');
var smoosher = require('gulp-smoosher');
var rename = require('gulp-rename');
var fs = require('fs');

var browserSync = require('browser-sync');
var reload = browserSync.reload;

var assetPaths = {
  scripts: ['assets/scripts/jquery.js',
            'assets/scripts/jquery.flexslider.js',
            'assets/scripts/site.js'],
  images:   'assets/images/**/*.jpg',
  fonts:    'assets/fonts/**/*',
  styles:   'assets/styles/site.scss',
  html:     './*.html'
}

var distPaths = {
  scripts: 'dist/scripts',
  images:  'dist/images',
  fonts:   'dist/fonts',
  styles:  'dist/styles'
}

gulp.task('sass', function() {
  gulp.src(assetPaths.styles)
    .pipe(sass({
      errLogToConsole: true,
      outputStyle: "compressed"
    }))
    .pipe(gulp.dest(distPaths.styles))
    .pipe(reload({stream: true}))
});

// Flexslider uses an icon font and our CSS has a relative path.
// Thus, we move fonts over to the dist folder as well
gulp.task('fonts', function() {
  gulp.src(assetPaths.fonts)
    .pipe(newer(distPaths.fonts))
    .pipe(gulp.dest(distPaths.fonts))
});

gulp.task('scripts', function() {
  // These files are processed in order, instead of globbing js/*
  // as site requires flexslider requires jquery
  gulp.src(assetPaths.scripts)
    .pipe(newer(distPaths.scripts + '/site.js'))
    .pipe(uglify())
    .pipe(concat('site.js'))
    .pipe(gulp.dest(distPaths.scripts))
});

gulp.task('images', function () {
  gulp.src(assetPaths.images)
    .pipe(newer(distPaths.images))
    .pipe(imagemin({
      progressive: true,
      optimizationLevel: 5,
    }))
    .pipe(gulp.dest(distPaths.images))
});

gulp.task('serve', ['sass'], function() {
  browserSync({
    server: "./"
  });

  gulp.watch(assetPaths.scripts, ['scripts']).on('change', reload);
  gulp.watch(assetPaths.styles, ['sass']);
  gulp.watch(assetPaths.images, ['images']).on('change', reload);
  gulp.watch(assetPaths.html).on('change', reload);
});

gulp.task('criticalCSS', function(cb) {
  fs.writeFile('dist/styles/inline.css', '');
  critical.generate({
    base: './',
    src: 'index.html',
    dest: 'dist/styles/inline.css',
    minify: true,
    width: 1024,
    height: 768
  })
  cb();
})

gulp.task('inlineCriticalCSS', function() {
  return gulp.src('./index.html')
    .pipe(rename({suffix: '-inline' }))
    .pipe(smoosher())
    .pipe(gulp.dest('./'));
});

// When running the Styles task, move over fonts before compiling Sass
gulp.task('styles', ['fonts', 'sass'])

gulp.task('inline', ['criticalCSS', 'inlineCriticalCSS'])

gulp.task('default', ['styles', 'scripts', 'images'])


text:
import time
from tentacle_pi.AM2315 import AM2315
from tentacle_pi.BMP180 import BMP180
from tentacle_pi.TSL2561 import TSL2561
from tentacle_pi.MCP9808 import MCP9808
from tentacle_pi.MPL115A2 import MPL115A2
from tentacle_pi.LM75 import LM75

"""
Simple test to check if all supported sensors are working.

- Runs on a Odroid C1 (Ubuntu) and Raspberry Pi 1 / 2 (Raspbian).
- For the Banana Pi (Raspbian) change the variable I2C_DEVICE to '/dev/i2c-2'

"""

I2C_DEVICE = '/dev/i2c-1'

print "test AM2315"
am = AM2315(0x5c, I2C_DEVICE)
temperature, humidity, crc_check = am.sense()
print "temperature: %0.1f" % temperature
print "humidity: %0.1f" % humidity
print "crc: %s" % crc_check
print
time.sleep(2)

print "test BMP180"
bmp = BMP180(0x77, I2C_DEVICE)
print "temperature: %0.1f" % bmp.temperature()
print "pressure: %s" % bmp.pressure()
print "altitude: %0.1f" % bmp.altitude()
print
time.sleep(2)

print "test TSL2561"
tsl = TSL2561(0x39, I2C_DEVICE)
tsl.enable_autogain()
tsl.set_time(0x00)
print "lux %s" % tsl.lux()
print
time.sleep(2)

print "test MCP9808"
mcp = MCP9808(0x18, I2C_DEVICE)
temperature = mcp.temperature()
print "temperature: %0.2f" % temperature
print
time.sleep(2)

print "test MPL115A2"
mpl = MPL115A2(0x60, I2C_DEVICE)
temperature, pressure = mpl.temperature(), mpl.pressure()
print "temperature: %0.1f" % temperature
print "pressure: %0.1f" % pressure
print
time.sleep(2)

print "test LM75"
lm = LM75(0x48, I2C_DEVICE)
temperature = lm.temperature()
print "temperature: %0.2f" % temperature
time.sleep(2)


text:
package com.smartsheet.api.internal;

import com.smartsheet.api.GroupMemberResources;
import com.smartsheet.api.GroupResources;
import com.smartsheet.api.SmartsheetException;
import com.smartsheet.api.internal.util.Util;
import com.smartsheet.api.models.Group;
import com.smartsheet.api.models.PagedResult;
import com.smartsheet.api.models.PaginationParameters;

/**
 * This is the implementation of the HomeResources.
 *
 * Thread Safety: This class is thread safe because it is immutable and its base class is thread safe.
 */
public class GroupResourcesImpl extends AbstractResources implements GroupResources {
    private GroupMemberResources groupMemberResources;
    /**
     * Constructor.
     *
     * Exceptions: - IllegalArgumentException : if any argument is null
     *
     * @param smartsheet the smartsheet
     */
    public GroupResourcesImpl(SmartsheetImpl smartsheet) {
        super(smartsheet);
        this.groupMemberResources = new GroupMemberResourcesImpl(smartsheet, "group");
    }

    @Override
    public PagedResult<Group> listGroups(PaginationParameters paging) throws SmartsheetException {
        String path = "groups";

        if (paging != null) {
            path += paging.toQueryString();
        }

        return this.listResourcesWithWrapper(path, Group.class);
    }

    @Override
    public Group getGroup(long groupId) throws SmartsheetException {
        return this.getResource("groups/" + groupId, Group.class);
    }

    @Override
    public Group createGroup(Group group) throws SmartsheetException {
        Util.throwIfNull(group);
        return this.createResource("groups", Group.class, group);
    }

    @Override
    public Group updateGroup(Group group) throws SmartsheetException {
        Util.throwIfNull(group);
        return this.updateResource("groups/"+ group.getId(), Group.class, group);
    }

    @Override
    public void deleteGroup(long groupId) throws SmartsheetException {
        this.deleteResource("groups/" + groupId, Group.class);
    }

    @Override
    /**
     * Represents the GroupMemberResources.
     * It will be initialized in constructor and will not change afterwards.
     *
     * @return members object
     * @throws SmartsheetException if there is any other error during the operation
     */
    public GroupMemberResources memberResources() throws SmartsheetException {
        return groupMemberResources;
    }
}


text:
layout: post
title: "Git Ninya Class comes to Istanbul"
date: "2014-07-05"
summary: Today we are happy to announce that our Git Ninja Class is coming to Istanbul!

categories:
  - announcements
author: pascal_precht
---

Today we are happy to announce that our **Git Ninja Class** is coming to Istanbul!

At thoughtram we are commited to run workshops online and offline. Every once in a while we try to bring our offline workshops to a new city. Yes, we love chats and hangouts as well but we also value being physically in one room together.

Istanbul is the largest city in Turkey with a vibrant tech scene. We are happy to have a strong partner in Istanbul to support us with all local affairs.

<img alt="webbox.io logo" style="max-width: 250px;" src="http://webbox.io/images/logo/logo-250px.png">

The workshop will be held on **13th + 14th of September 2014**.

If you like to attend this workshop please head over to [the webbox.io website](http://webbox.io/workshops/git-ninja/) for more details and booking.

Like to see Git Ninja Class in your city? Drop us an email at hello@thoughtram.io

-- Pascal & Christoph


text:
module Police
  class Middleware
    include Rack
    include ActionView

    def initialize(app)
      @app = app
    end

    def label_hash(h, label)
      h.each do |k, v|
        if v.is_a? Hash
          # puts "Rack: labeling a hash #{h}"
          v = label_hash v, label
        else
          # puts "Rack: labeling value #{v}"
          v.label_with label
        end
      end

      h
    end

    def call(env)
      # puts "POLICE MIDDLEWARE DOING STUFF"
      user_supplied_label = Police::DataFlow::UserSupplied.new

      req = Rack::Request.new(env)

      # puts "Request params #{req.params}"

      req.params.each do |k, v|
        if v.is_a? Hash
          # puts "Rack: labeling a hash #{v} start"
          v = label_hash(v, user_supplied_label)
          req.update_param k, v
        else
          # puts "Rack: labeling #{k}'s value #{v}"
          req.update_param k, v.label_with(user_supplied_label)
        end
      end

      # ['QUERY_STRING', 'REQUEST_URI', 'ORIGINAL_FULLPATH', 'rack.request.query_string', 'rack.request.form_vars'].each do |user_supplied_data|
      #   # puts "Labeling env param #{user_supplied_data}, #{env[user_supplied_data]}"
      #   env[user_supplied_data].label_with user_supplied_label
      # end

      # ['rack.request.form_hash', 'rack.request.query_hash'].each do |user_supplied_data|
      #   puts "Labeling env hash #{user_supplied_data}, #{env[user_supplied_data]}"
      #   label_hash env[user_supplied_data], user_supplied_label if env[user_supplied_data]
      # end

      env['police.from_user_label'] = user_supplied_label

      env['police.set_user'] = lambda do |user|
        user_supplied_label.payload = user
      end

      status, headers, response = @app.call(env)

      if response.is_a? Rack::BodyProxy
        response.each do |v|
          puts "Checking dataflow on output. Output has #{v.labels.size} labels"

          v.labels.each do |label|
            case label
            when Police::DataFlow::ReadRestriction
              puts "Have a read restriction"
              origin = label.payload
              origin.enforce_read_restrictions env['police.from_user_label'].payload
              # Figure out santization rules so that this doesn't always propagate
              # when Police::DataFlow::UserSupplied
              #   raise Police::PoliceError, "unsanitized user supplied string at output"
            end
          end
        end
      end

      # puts "Status is #{status}, #{response}"
      # response.each do |v|
      # 	puts v
      # end
      return status, headers, response
    end
  end
end


text:
//
//  LZGPublishView.m
//  百思不得姐
//
//  Created by 浮云漫步 on 16/5/28.
//  Copyright © 2016年 iphone. All rights reserved.
//

#import "LZGPublishView.h"
#import "LZGVerticaButton.h"
#import <POP.h>
#import "XMGPostWordViewController.h"

@implementation LZGPublishView

- (void)awakeFromNib{

    [UIApplication sharedApplication].keyWindow.rootViewController.view.userInteractionEnabled = NO;
    self.userInteractionEnabled = NO;

    // 数据
    NSArray *images = @[@"publish-video", @"publish-picture", @"publish-text", @"publish-audio", @"publish-review", @"publish-offline"];
    NSArray *titles = @[@"发视频", @"发图片", @"发段子", @"发声音", @"审帖", @"离线下载"];

    /**
     *  中间的六个按钮
     */
    CGFloat buttonW = 72;
    CGFloat buttonH = buttonW + 30;
    int maxCols = 3;
    CGFloat maginX = 20;
    CGFloat buttonStartY = (LZGScreenH - 2 * buttonH) * 0.5;
    CGFloat TwoMaginX = (LZGScreenW - 2 * maginX - maxCols * buttonW) / (maxCols - 1);

    for (int i = 0; i < images.count; i ++) {
        LZGVerticaButton *btn = [[LZGVerticaButton alloc]init];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [btn setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn setTitle:titles[i] forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont systemFontOfSize:14];
        btn.tag = i;
        /**
         *  设置frame
         */
        int row = i / maxCols;//行
        int col = i % maxCols;//列
        CGFloat btnX = maginX + col * (buttonW + TwoMaginX);
        CGFloat btnY = buttonStartY + row * buttonH;

//        btn.frame = CGRectMake(btnX, btnY, buttonW, buttonH);
        [self addSubview:btn];

        POPSpringAnimation *anim = [POPSpringAnimation animationWithPropertyNamed:kPOPViewFrame];
        anim.fromValue = [NSValue valueWithCGRect:CGRectMake(btnX, btnY - LZGScreenH, buttonW, buttonH)];
        anim.toValue = [NSValue valueWithCGRect:CGRectMake(btnX, btnY, buttonW, buttonH)];
        anim.springSpeed = 10;
        anim.springBounciness = 10;
        anim.beginTime = CACurrentMediaTime() + 0.1 * i;
        [btn pop_addAnimation:anim forKey:nil];
    }
    /**
     添加图标
     */
    UIImageView *sloganView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"app_slogan"]];
//    sloganView.y = LZGScreenH * 0.2;
//    sloganView.centerX = LZGScreenW * 0.5;
    [self addSubview:sloganView];

    POPSpringAnimation *anim1 = [POPSpringAnimation animationWithPropertyNamed:kPOPViewCenter];
    CGFloat centerX = LZGScreenW * 0.5;
    CGFloat centerEndY = LZGScreenH * 0.2;
    CGFloat centerBeginY = centerEndY - centerX;
    sloganView.centerY = centerBeginY;
    anim1.fromValue = [NSValue valueWithCGPoint:CGPointMake(centerX, 0)];
    anim1.toValue = [NSValue valueWithCGPoint:CGPointMake(centerX, centerEndY)];
    anim1.springSpeed = 10;
    anim1.springBounciness = 10;
    anim1.beginTime = CACurrentMediaTime() + 0.05 * images.count;
    [anim1 setCompletionBlock:^(POPAnimation *anim, BOOL finish) {
          [UIApplication sharedApplication].keyWindow.rootViewController.view.userInteractionEnabled = YES;
        self.userInteractionEnabled = YES;
    }];
    [sloganView pop_addAnimation:anim1 forKey:nil];
}
- (IBAction)cancel{
    [self cancelWithCompletionBlick:nil];
}

/**
 *  先执行退出动画,再执行completion"Block"
 */
- (void)cancelWithCompletionBlick:(void(^)())completion{
    [UIApplication sharedApplication].keyWindow.rootViewController.view.userInteractionEnabled = NO;
    self.userInteractionEnabled = NO;
    for (int i = 2; i < self.subviews.count; i ++) {
        UIView *subView = self.subviews[i];
        POPSpringAnimation *spring = [POPSpringAnimation animationWithPropertyNamed:kPOPViewCenter];
        CGFloat centerY = subView.centerY + LZGScreenH;
        spring.toValue = [NSValue valueWithCGPoint:CGPointMake(subView.centerX, centerY)];
        spring.beginTime = CACurrentMediaTime() + (i - 2) * 0.05;
        //        spring.springSpeed = 10;
        //        spring.springBounciness = 10;
        [subView pop_addAnimation:spring forKey:nil];

        if (i == self.subviews.count - 1) {
            [spring setCompletionBlock:^(POPAnimation *ani, BOOL finish) {
                 [UIApplication sharedApplication].keyWindow.rootViewController.view.userInteractionEnabled = YES;
                [self removeFromSuperview];
                if (completion) {
                    completion();
                }
            }];
        }
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self cancelWithCompletionBlick:nil];
}
/**
 *  点击图标按钮后
 */
- (void)btnClick:(UIButton *)btn{
    [self cancelWithCompletionBlick:^{
        if (btn.tag == 2) {
            XMGPostWordViewController *post = [[XMGPostWordViewController alloc]init];
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:post];
            UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
            [vc presentViewController:nav animated:YES completion:nil];
        }
    }];
}
@end


text:
package org.apache.hadoop.hbase.quotas.policies;

import org.apache.hadoop.hbase.quotas.SpaceLimitingException;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;

/**
 * Test class for {@link NoWritesCompactionsViolationPolicyEnforcement};
 */
@Category(SmallTests.class)
public class TestNoWritesCompactionsViolationPolicyEnforcement
    extends BaseViolationPolicyEnforcement {

  private NoWritesCompactionsViolationPolicyEnforcement enforcement;

  @Before
  public void setup() {
    enforcement = new NoWritesCompactionsViolationPolicyEnforcement();
  }

  @Test(expected = SpaceLimitingException.class)
  public void testCheckAppend() throws Exception {
    enforcement.check(APPEND);
  }

  @Test(expected = SpaceLimitingException.class)
  public void testCheckDelete() throws Exception {
    enforcement.check(DELETE);
  }

  @Test(expected = SpaceLimitingException.class)
  public void testCheckIncrement() throws Exception {
    enforcement.check(INCREMENT);
  }

  @Test(expected = SpaceLimitingException.class)
  public void testCheckPut() throws Exception {
    enforcement.check(PUT);
  }
}