text:
package org.apereo.cas.oidc.claims;

import org.apereo.cas.authentication.CoreAuthenticationTestUtils;
import org.apereo.cas.oidc.AbstractOidcTests;
import org.apereo.cas.oidc.OidcConstants;
import org.apereo.cas.services.ChainingAttributeReleasePolicy;
import org.apereo.cas.services.util.RegisteredServiceJsonSerializer;
import org.apereo.cas.util.CollectionUtils;

import lombok.val;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.springframework.test.context.TestPropertySource;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

/**
 * This is {@link OidcEmailScopeAttributeReleasePolicyTests}.
 *
 * @author Misagh Moayyed
 * @since 6.1.0
 */
@Tag("OIDC")
@TestPropertySource(properties = {
    "cas.authn.oidc.core.claims-map.email=mail",
    "cas.authn.oidc.core.claims-map.email_verified=mail_confirmed"
})
public class OidcEmailScopeAttributeReleasePolicyTests extends AbstractOidcTests {
    @Test
    public void verifyOperation() {
        val policy = new OidcEmailScopeAttributeReleasePolicy();
        assertEquals(OidcConstants.StandardScopes.EMAIL.getScope(), policy.getScopeType());
        assertNotNull(policy.getAllowedAttributes());
        val principal = CoreAuthenticationTestUtils.getPrincipal(CollectionUtils.wrap("email", List.of("cas@example.org"),
            "email_verified", List.of("cas@example.org")));
        val attrs = policy.getAttributes(principal,
            CoreAuthenticationTestUtils.getService(),
            CoreAuthenticationTestUtils.getRegisteredService());
        assertTrue(policy.getAllowedAttributes().stream().allMatch(attrs::containsKey));
        assertTrue(policy.determineRequestedAttributeDefinitions().containsAll(policy.getAllowedAttributes()));
    }

    @Test
    public void verifyClaimMapOperation() {
        val policy = new OidcEmailScopeAttributeReleasePolicy();
        assertEquals(OidcConstants.StandardScopes.EMAIL.getScope(), policy.getScopeType());
        assertNotNull(policy.getAllowedAttributes());

        val principal = CoreAuthenticationTestUtils.getPrincipal(CollectionUtils.wrap("mail", List.of("cas@example.org"),
            "mail_confirmed", List.of("cas@example.org"), "phone", List.of("0000000000")));
        val attrs = policy.getAttributes(principal,
            CoreAuthenticationTestUtils.getService(),
            CoreAuthenticationTestUtils.getRegisteredService());
        assertEquals(List.of("cas@example.org"), attrs.get("email"));
        assertEquals(List.of("cas@example.org"), attrs.get("email_verified"));
        assertFalse(attrs.containsKey("phone"));

        val serviceTicketPrincipal = CoreAuthenticationTestUtils.getPrincipal(attrs);
        val releaseAttrs = policy.getAttributes(serviceTicketPrincipal,
            CoreAuthenticationTestUtils.getService(),
            CoreAuthenticationTestUtils.getRegisteredService());
        assertEquals(List.of("cas@example.org"), releaseAttrs.get("email"));
        assertEquals(List.of("cas@example.org"), releaseAttrs.get("email_verified"));
        assertFalse(releaseAttrs.containsKey("phone"));
    }

    @Test
    public void verifySerialization() {
        val policy = new OidcEmailScopeAttributeReleasePolicy();
        val chain = new ChainingAttributeReleasePolicy();
        chain.addPolicy(policy);
        val service = getOidcRegisteredService();
        service.setAttributeReleasePolicy(chain);
        val serializer = new RegisteredServiceJsonSerializer();
        val json = serializer.toString(service);
        assertNotNull(json);
        assertNotNull(serializer.from(json));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package de.lessvoid.nifty.controls.dragndrop.builder;

import de.lessvoid.nifty.builder.ControlBuilder;

public class DraggableBuilder extends ControlBuilder {
  public DraggableBuilder() {
    super("draggable");
  }

  public DraggableBuilder(final String id) {
    super(id, "draggable");
  }

  public void handle(final String handleId) {
    set("handle", handleId);
  }

  public void revert(final boolean revert) {
    set("revert", String.valueOf(revert));
  }

  public void drop(final boolean drop) {
    set("drop", String.valueOf(drop));
  }
}


text:
import logging
import datetime

from discord import User
from discord.ext import commands
from discord.ext.commands import Bot
from discord.ext.commands import Context

logger = logging.getLogger(__name__)

# Time where poll can only be closed by owner or channel managers
DEFAULT_LOCK_TIME = datetime.timedelta(hours=6)

class PollState:
    """State of a single poll.

     Attributes
    -----------
    owner : User
        Owner of this poll.
    question : str
        The poll question.
    choices : List[str]
        List of choices.
    voters : Set[User]
        Voters who have already voted in this poll.
    original_message: Message
        The message sent by the bot when the poll was started showing the state
        of the poll. It will be updated continuously as votes are submitted.
    """

    def __init__(self, owner: User, question: str, choices):
        self.owner = owner
        self.question = question
        self.choices = [{'name': choice, 'count': 0} for choice in choices]
        self.voters = set()
        self.original_message = None
        self.start_time = datetime.datetime.now()

    def __str__(self):
        choice_list = [
            '{}. {} - {} vote(s)'.format(i + 1, ans['name'], ans['count'])
            for i, ans in enumerate(self.choices)
        ]

        return '{}\n\n{}'.format(self.question, '\n'.join(choice_list))

    def end_result_str(self):
        max_votes = max(self.choices, key=lambda ans: ans['count'])['count']
        choice_list = [
            '{0}{1}. {2} - {3} vote(s){0}'.format(
                '**' if ans['count'] == max_votes else '',
                i + 1, ans['name'], ans['count'])
            for i, ans in enumerate(self.choices)
        ]

        return '**POLL RESULTS**: {}\n\n{}'.format(
            self.question, '\n'.join(choice_list))

    def get_validated_choice(self, ans_num):
        try:
            ans_num = int(ans_num)
            return ans_num if 1 <= ans_num <= len(self.choices) else None
        except (TypeError, ValueError):
            return None

    def has_already_voted(self, user):
        return user in self.voters

    def has_lock_expired(self):
        return datetime.datetime.now() - self.start_time > DEFAULT_LOCK_TIME

class Poll:
    """Commands to create and manage polls."""

    def __init__(self, bot):
        self.bot = bot
        self.current_polls = {}

    @commands.group(pass_context=True)
    async def poll(self, ctx: Context):
        """Group of commands for poll management"""
        if ctx.invoked_subcommand is not None:
            return

        channel = ctx.message.channel
        if channel in self.current_polls:
            await self.bot.say('Current poll: {}'.format(
                self.current_polls[channel]))
        else:
            await self.bot.say('There is no poll currently running.')

    @poll.command(pass_context=True)
    async def start(self, ctx: Context, question=None, *choices):
        """Start a poll.

        Syntax:
            /poll start "This is the question" "Choice 1" "Choice 2"
        """
        if question is None:
            await self.bot.reply('your poll needs a question.')
            return

        if len(choices) < 1:
            await self.bot.reply('your poll needs choices.')
            return

        channel = ctx.message.channel
        if channel in self.current_polls:
            await self.bot.reply('there is already a poll running in here.')
            return

        current_poll = PollState(ctx.message.author, question, choices)

        self.current_polls[channel] = current_poll

        message = await self.bot.say('**POLL**: {}'.format(current_poll))
        current_poll.original_message = message
        await self.bot.pin_message(message)

    @poll.command(pass_context=True, aliases=['end'])
    async def stop(self, ctx: Context):
        """Stop the current poll.

        When the poll is locked, only the poll owner or users who have the
        Manage Messages permission for the channel can stop the poll.
        """
        channel = ctx.message.channel
        if channel not in self.current_polls:
            await self.bot.reply('there is no poll currently running in here.')
            return

        current_poll = self.current_polls[channel]
        author = ctx.message.author
        if not (author == current_poll.owner or
                author.permissions_in(channel).manage_messages or
                current_poll.has_lock_expired()):
            await self.bot.reply("you can't end this poll yet.")
            return

        self.current_polls.pop(channel)
        await self.bot.unpin_message(current_poll.original_message)
        await self.bot.say(current_poll.end_result_str())

    @commands.command(pass_context=True)
    async def vote(self, ctx: Context, ans_num=None):
        """Vote for a choice. Must be a choice number."""
        channel = ctx.message.channel
        if channel not in self.current_polls:
            await self.bot.reply('there is no poll currently running in here.')
            return

        current_poll = self.current_polls[channel]

        ans_num = current_poll.get_validated_choice(ans_num)
        if ans_num is None:
            await self.bot.reply('your vote must be between {}-{}.'.format(
                1, len(current_poll.choices)))
            return

        author = ctx.message.author
        if current_poll.has_already_voted(author):
            await self.bot.reply('you have already voted in this poll.')
            return

        current_poll.choices[ans_num - 1]['count'] += 1
        current_poll.voters.add(author)
        await self.bot.edit_message(current_poll.original_message,
                                    str(current_poll))
        await self.bot.reply('your vote has been counted.')

def setup(bot: Bot):
    bot.add_cog(Poll(bot))


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  	<modelVersion>4.0.0</modelVersion>
	<groupId>org.overlord.rtgov.samples.karaf.policy</groupId>
	<artifactId>samples-karaf-policy-async-av</artifactId>
	<packaging>bundle</packaging>
	<name>Overlord RTGov::Samples::Karaf::Policy::Async AV</name>

	<parent>
		<groupId>org.overlord.rtgov.samples.karaf</groupId>
		<artifactId>policy</artifactId>
		<version>2.2.0-SNAPSHOT</version>
	</parent>

	<dependencies>
		<dependency>
			<groupId>org.overlord.rtgov.activity-management</groupId>
			<artifactId>av-loader-osgi</artifactId>
		</dependency>
		<dependency>
			<groupId>org.overlord.rtgov.activity-management</groupId>
			<artifactId>activity</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.overlord.rtgov.common</groupId>
			<artifactId>rtgov-infinispan</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.overlord.rtgov.common</groupId>
			<artifactId>rtgov-common</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.overlord.rtgov.active-queries</groupId>
			<artifactId>active-collection</artifactId>
			<scope>provided</scope>
		</dependency>

		<dependency>
			<groupId>org.hibernate.javax.persistence</groupId>
			<artifactId>hibernate-jpa-2.0-api</artifactId>
			<scope>provided</scope>
		</dependency>

		<!-- The following dependencies are only required for testing the EPN -->

		<dependency>
			<groupId>org.overlord.rtgov.event-processor</groupId>
			<artifactId>ep-core</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.overlord.rtgov.event-processor</groupId>
			<artifactId>ep-mvel</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.infinispan</groupId>
			<artifactId>infinispan-core</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.logging</groupId>
			<artifactId>jboss-logging</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jgroups</groupId>
			<artifactId>jgroups</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.marshalling</groupId>
			<artifactId>jboss-marshalling</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jboss.marshalling</groupId>
			<artifactId>jboss-marshalling-river</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-core-asl</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mvel</groupId>
			<artifactId>mvel2</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.enterprise</groupId>
			<artifactId>cdi-api</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<finalName>policy-async-av</finalName>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
 				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
						<Bundle-Version>${project.version}</Bundle-Version>
						<Bundle-Activator>org.overlord.rtgov.activity.validator.loader.osgi.AVActivator</Bundle-Activator>
						<Import-Package>
							!javax.inject.*,!javax.enterprise.*,!javax.persistence.*,
							org.overlord.rtgov.ep,org.overlord.rtgov.ep.mvel,
							org.overlord.rtgov.active.collection,
							org.overlord.rtgov.active.collection.service,
							org.overlord.rtgov.activity.model,
							org.overlord.rtgov.activity.model.app,
							org.overlord.rtgov.activity.model.bpm,
							org.overlord.rtgov.activity.model.common,
							org.overlord.rtgov.activity.model.mom,
							org.overlord.rtgov.activity.model.soa,
							*
						</Import-Package>
						<Embed-Dependency>*;scope=compile|runtime</Embed-Dependency>
					</instructions>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>


text:
class AddBlogsCommentCountToUser < ActiveRecord::Migration
  def change
    add_column :users, :blogs_comment_count, :integer
  end
end


text:
@extends('layouts.backend')

@section('styles')
	<link href='http://fonts.googleapis.com/css?family=Droid+Serif' rel='stylesheet' type='text/css'>
	<link rel="stylesheet" href="{{ URL::asset('css/widearea.min.css') }}">
	<link rel="stylesheet" href="{{ URL::asset('css/dropzone.min.css') }}">
@stop

@section('scripts')

@stop

@section('content')

Post a new article

				<form class="form-horizontal" method="post">

						Title

							<input type="text" name="text" class="form-control" id="input-title" placeholder="The name of your article" value="{{ Input::old('title') }}" required>

						Slug

							<input type="text" name="slug" class="form-control" id="input-slug" placeholder="The URL access point of your article" value="{{ Input::old('slug') }}" required>

						Content

							<textarea data-widearea="enable" name="content" id="input-content" cols="30" rows="10" class="form-control" placeholder="The content of your article" required>{{ Input::old('content') }}</textarea>

									<input type="checkbox" id="input-publish" name="publish"> Publish article immediately?

							<input type="hidden" name="_token" value="{{ csrf_token() }}">
							<button type="submit" class="btn btn-success btn-sm" id="input-submit">Save draft</button>

				</form>

				<form action="/backend/upload" id="image-upload" class="dropzone">
					<input type="hidden" name="_token" value="{{ csrf_token() }}">
				</form>

@stop


text:
package org.algo.matrix.decomposition;

import java.math.BigDecimal;

import org.algo.ProgrammingError;
import org.algo.access.Access2D;
import org.algo.array.Array1D;
import org.algo.array.DenseArray;
import org.algo.matrix.store.MatrixStore;
import org.algo.scalar.ComplexNumber;
import org.algo.type.context.NumberContext;

/**
 * Singular Value: [A] = [Q1][D][Q2]T Decomposes [this] into [Q1], [D] and [Q2] where:
 *

 *
[Q1] is an orthogonal matrix. The columns are the left, orthonormal, singular vectors of [this]. Its
 * columns are the eigenvectors of [A][A]T, and therefore has the same number of rows as [this].
 *

 *
[D] is a diagonal matrix. The elements on the diagonal are the singular values of [this]. It is either
 * square or has the same dimensions as [this]. The singular values of [this] are the square roots of the
 * nonzero eigenvalues of [A][A]T and [A]T[A] (they are the same)

 *
[Q2] is an orthogonal matrix. The columns are the right, orthonormal, singular vectors of [this]. Its
 * columns are the eigenvectors of [A][A]T, and therefore has the same number of rows as [this] has
 * columns.

 *
[this] = [Q1][D][Q2]T

 *

 * A singular values decomposition always exists.
 *
 * @author apete
 */
public interface SingularValue<N extends Number> extends MatrixDecomposition<N>, MatrixDecomposition.Solver<N>, MatrixDecomposition.EconomySize<N>,
        MatrixDecomposition.RankRevealing<N>, MatrixDecomposition.Values<N> {

    interface Factory<N extends Number> extends MatrixDecomposition.Factory<SingularValue<N>> {

    }

    public static final Factory<BigDecimal> BIG = typical -> new SingularValueDecomposition.Big();

    public static final Factory<ComplexNumber> COMPLEX = typical -> new SingularValueDecomposition.Complex();

    public static final Factory<Double> PRIMITIVE = typical -> {
        if ((1024L < typical.countColumns()) && (typical.count() <= DenseArray.MAX_ARRAY_SIZE)) {
            return new SingularValueDecomposition.Primitive();
        } else {
            return new RawSingularValue();
        }
    };

    @SuppressWarnings("unchecked")
    public static <N extends Number> SingularValue<N> make(final Access2D<N> typical) {

        final N tmpNumber = typical.get(0, 0);

        if (tmpNumber instanceof BigDecimal) {
            return (SingularValue<N>) BIG.make(typical);
        } else if (tmpNumber instanceof ComplexNumber) {
            return (SingularValue<N>) COMPLEX.make(typical);
        } else if (tmpNumber instanceof Double) {
            return (SingularValue<N>) PRIMITIVE.make(typical);
        } else {
            throw new IllegalArgumentException();
        }
    }

    static <N extends Number> boolean equals(final MatrixStore<N> matrix, final SingularValue<N> decomposition, final NumberContext context) {

        final int tmpRowDim = (int) matrix.countRows();
        final int tmpColDim = (int) matrix.countColumns();

        final MatrixStore<N> tmpQ1 = decomposition.getQ1();
        final MatrixStore<N> tmpD = decomposition.getD();
        final MatrixStore<N> tmpQ2 = decomposition.getQ2();

        MatrixStore<N> tmpThis;
        MatrixStore<N> tmpThat;

        boolean retVal = (tmpRowDim == tmpQ1.countRows()) && (tmpQ2.countRows() == tmpColDim);

        // Check that [A][Q2] == [Q1][D]
        if (retVal) {

            tmpThis = matrix.multiply(tmpQ2);
            tmpThat = tmpQ1.multiply(tmpD);

            retVal &= tmpThis.equals(tmpThat, context);
        }

        // If Q1 is square, then check if it is orthogonal/unitary.
        if (retVal && (tmpQ1.countRows() == tmpQ1.countColumns())) {

            tmpThis = tmpQ1.physical().makeEye(tmpRowDim, tmpRowDim);
            tmpThat = tmpQ1.logical().conjugate().get().multiply(tmpQ1);

            retVal &= tmpThis.equals(tmpThat, context);
        }

        // If Q2 is square, then check if it is orthogonal/unitary.
        if (retVal && (tmpQ2.countRows() == tmpQ2.countColumns())) {

            tmpThis = tmpQ2.physical().makeEye(tmpColDim, tmpColDim);
            tmpThat = tmpQ2.multiply(tmpQ2.logical().conjugate().get());

            retVal &= tmpThis.equals(tmpThat, context);
        }

        // Check the pseudoinverse.
        if (retVal) {
            retVal &= matrix.equals(matrix.multiply(decomposition.getInverse().multiply(matrix)), context);
        }

        // Check that the singular values are sorted in descending order
        if (retVal) {
            final Array1D<Double> tmpSV = decomposition.getSingularValues();
            for (int i = 1; retVal && (i < tmpSV.size()); i++) {
                retVal &= tmpSV.doubleValue(i - 1) >= tmpSV.doubleValue(i);
            }
            if (retVal && decomposition.isOrdered()) {
                for (int ij = 1; retVal && (ij < tmpD.countRows()); ij++) {
                    retVal &= tmpD.doubleValue(ij - 1, ij - 1) >= tmpD.doubleValue(ij, ij);
                }
            }
        }

        return retVal;
    }

    static <N extends Number> MatrixStore<N> reconstruct(final SingularValue<N> decomposition) {
        return decomposition.getQ1().multiply(decomposition.getD()).multiply(decomposition.getQ2().conjugate());
    }

    /**
     * The condition number.
     *
     * @return The largest singular value divided by the smallest singular value.
     */
    double getCondition();

    /**
     * @return The diagonal matrix of singular values.
     */
    MatrixStore<N> getD();

    /**
     * Sometimes also called the Schatten 2-norm or Hilbert-Schmidt norm.
     *
     * @return The square root of the sum of squares of the singular values.
     */
    double getFrobeniusNorm();

    /**
     *

     * Ky Fan k-norm.
     *

     *

     * The first Ky Fan k-norm is the operator norm (the largest singular value), and the last is called the
     * trace norm (the sum of all singular values).
     *

     *
     * @param k The number of singular values to add up.
     * @return The sum of the k largest singular values.
     */
    double getKyFanNorm(int k);

    /**
     * @return 2-norm
     */
    double getOperatorNorm();

    /**
     * If [A] is m-by-n and its rank is r, then:
     *

     *
The first r columns of [Q1] span the column space, range or image of [A].

     *
The last m-r columns of [Q1] span the left nullspace or cokernel of [A].

     *

     * Calculating the QR decomposition of [A] is a faster alternative.
     */
    MatrixStore<N> getQ1();

    /**
     * If [A] is m-by-n and its rank is r, then:
     *

     *
The first r columns of [Q2] span the row space or coimage of [A].

     *
The last n-r columns of [Q2] span the nullspace or kernel of [A].

     *

     * Calculating the QR decomposition of [A]T is a faster alternative.
     */
    MatrixStore<N> getQ2();

    /**
     * @return The singular values ordered in descending order.
     */
    Array1D<Double> getSingularValues();

    /**
     * @param values An array that will receive the singular values
     */
    default void getSingularValues(final double[] values) {

        ProgrammingError.throwIfNull(values);

        final Array1D<Double> singulars = this.getSingularValues();

        final int length = values.length;
        for (int i = 0; i < length; i++) {
            values[i] = singulars.doubleValue(i);
        }
    }

    double getTraceNorm();

    default MatrixStore<N> reconstruct() {
        return SingularValue.reconstruct(this);
    }

}


text: module.exports = require('./lib/connect-mysql-session');


text:
class ScopeFormsToConventions < ActiveRecord::Migration[5.1]
  def change
    add_reference :forms, :convention, foreign_key: true
  end
end


text:
using namespace bb::cascades;
using namespace bb::data;
using namespace bb::device;
using namespace bb::system;

NewsSpot::NewsSpot(bb::platform::bbm::Context &context, bb::cascades::Application *app)
: QObject(app)
, m_messageService(0)
, m_context(&context)
{
	DataSource::registerQmlTypes();
	qmlRegisterType<QTimer>("newsspot.timer", 1, 0, "Timer");
	qmlRegisterType<NetImageTracker>("newsspot.netimage", 1, 0, "NetImageTracker");
	qmlRegisterType<NetImageManager>("newsspot.netimage", 1, 0, "NetImageManager");
	qmlRegisterType<SystemDialog>("bb.system", 1, 0, "SystemDialog");
	qmlRegisterType<SystemToast>("bb.system", 1, 0, "SystemToast");
	qmlRegisterUncreatableType<TaskId>("newsspot.data", 1, 0, "TaskId", "Uncreatable type");
	qmlRegisterType<DataService>("newsspot.data", 1, 0, "DataService");
	qmlRegisterType<PullToRefresh>("newsspot.pulltorefresh", 1, 0, "PullToRefresh");
	qmlRegisterType<EditViewModel>("newsspot.models", 1, 0, "EditViewModel");
	qmlRegisterType<FeedsViewModel>("newsspot.models", 1, 0, "FeedsViewModel");

	initDb();

    // create scene document from main.qml asset
    // set parent to created document to ensure it exists for the whole application lifetime
    QmlDocument *qml = QmlDocument::create("asset:///main.qml").parent(this);
    DisplayInfo display;
	int width = display.pixelSize().width();
	int height = display.pixelSize().height();

	QDeclarativePropertyMap* displayProperties = new QDeclarativePropertyMap;
	displayProperties->insert("width", QVariant(width));
	displayProperties->insert("height", QVariant(height));

	qml->setContextProperty("DisplayInfo", displayProperties);
    qml->setContextProperty("cs", this);

    // create root object for the UI
    AbstractPane *root = qml->createRootObject<AbstractPane>();
    // set created root object as a scene
    app->setScene(root);

    deserializeObject();

    connect(Application::instance(), SIGNAL(aboutToQuit()), this, SLOT(onExit()));
}

QString NewsSpot::findImage(const QVariant item)
{
    // The item variable is the xml data from rss-feed
    QVariantMap itemData = item.toMap();

    // Some streams have the image data in a media:content container, of so let's get it
    if (itemData.contains("media:content")) {
        QVariantMap itemMediaMap;

        if (itemData["media:content"].canConvert<QVariantList>()) {
            QVariantList itemMediaList = itemData["media:content"].toList();

            if (itemMediaList.size() > 0) {
                itemMediaMap = itemMediaList.at(1).toMap();
            } else {
                itemMediaMap = itemMediaList.at(0).toMap();
            }

        } else if (itemData["media:content"].canConvert<QVariantMap>()) {
            itemMediaMap = itemData["media:content"].toMap();

        } else {
            // Well, there was some new way we have not encountered before
            qDebug() << "could not convert " << itemData["media:content"];
        }
        // Sometimes it's an URL
        if (itemMediaMap.contains("url")) {
            return itemMediaMap["url"].toString();
        }
    // If the image data is not in media:content it could be in content:encoded, let's check here
    } else {
        // We might find the image data in either the content:encoded or the description part
        QString description;
        if (itemData.contains("content:encoded")) {
            description = itemData["content:encoded"].toString();
        }

        if (description.isNull() && itemData.contains("description")) {
            description = itemData["description"].toString();
        }

        if (!description.isNull()) {
            // Grab the first img tag in the description and use it as source
            int firstIndex = description.indexOf(QRegExp("<img [^>]*"));
            int sourceIndexStart = description.indexOf("src=\"", firstIndex) + 5;
            int sourceIndexEnd = description.indexOf('"', sourceIndexStart);

            QString imageUrl = description.mid(sourceIndexStart, sourceIndexEnd - sourceIndexStart);

            if (!imageUrl.isEmpty()) {
            	if (imageUrl.contains("http:")) {
            	    return imageUrl;
            	}
            	if (imageUrl.startsWith("//")) {
            		imageUrl = "http:" + imageUrl;
            		return imageUrl;
            	}
            }
        }
    }
    // We found nothing, return with sadness
    return "";
}

QString NewsSpot::plainText(const QString htmlString)
{
    // Remove all tags using a regular expression and returned the stripped string.
    QString plainString = htmlString;
    plainString.remove(QRegExp("<[^>]*>"));

    return plainString;
}

void NewsSpot::sendInvite() {
    if (!m_messageService) {
        // Instantiate the BBM MessageService.
        m_messageService = new bb::platform::bbm::MessageService(m_context, this);
    }

    // Trigger the invite to download process.
    m_messageService->sendDownloadInvitation();
}

void NewsSpot::initDb() {
	// From QuotesHelper app
	// Since we need read and write access to the file, it has
	// to be moved to a folder where we have access to it. First,
	// we check if the file already exists (previously copied).
	QString fileName("sql/data.db");
	QString dataFolder = QDir::homePath();
	QString newFileName = dataFolder + "/" + fileName;
	QFile newFile(newFileName);

	if (!newFile.exists()) {
		// If the file is not already in the data folder, we copy it from the
		// assets folder (read only) to the data folder (read and write).
		QString appFolder(QDir::homePath());
		appFolder.chop(4);
		QString originalFileName = appFolder + "app/native/assets/" + fileName;
		QFile originalFile(originalFileName);

		if (originalFile.exists()) {
			// Create sub folders if any creates the SQL folder for a file path like e.g. sql/quotesdb
			QFileInfo fileInfo(newFileName);
			QDir().mkpath (fileInfo.dir().path());

			if(!originalFile.copy(newFileName)) {
				qDebug() << "Failed to copy file to path: " << newFileName;
			}
		} else {
			qDebug() << "Failed to copy file data base file does not exists.";
		}
	}
}

QByteArray NewsSpot::getByteArray(const QString &string) {
	return string.toAscii();
}

void NewsSpot::clearCache() {
	QString diskPath = QDir::homePath() + "/feedImageManager/";
	removeDir(diskPath);
	diskPath = QDir::homePath() + "/feedIconManager/";
	removeDir(diskPath);
}

bool NewsSpot::removeDir(const QString &dirName) {
	bool result = true;
	QDir dir(dirName);

	if (dir.exists(dirName)) {
		Q_FOREACH(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot | QDir::System | QDir::Hidden  | QDir::AllDirs | QDir::Files, QDir::DirsFirst)) {
			if (info.isDir()) {
				result = removeDir(info.absoluteFilePath());
			}
			else {
				result = QFile::remove(info.absoluteFilePath());
			}

			if (!result) {
				return result;
			}
		}
		result = dir.rmdir(dirName);
	}

	return result;
}

void NewsSpot::setReadForKey(const QString &url) {
	QString hashedUrl = QString::number(qHash(url));
	m_readStatusList.insert(hashedUrl, QVariant(true));
	m_readExpiryList.insert(hashedUrl, QVariant(QDateTime::currentDateTime()));
}

bool NewsSpot::isReadForKey(const QString &url) {
	QVariant read = m_readStatusList.value(QString::number(qHash(url)));
	if (read.canConvert<bool>()) {
		return read.toBool();
	}
	return false;
}

void NewsSpot::serializeObject() {
	// call on app shutdown
	houseKeepReadStatus();

	QFile file("./data/ReadUnreadList.dat");
	if (!file.open(QIODevice::WriteOnly)) {
		return;
	}
	QDataStream out(&file);
	if (out.status() == QDataStream::Ok) {
		out << m_readStatusList;
	}
	file.close();

	QFile file1("./data/ReadExpiryList.dat");
	if (!file1.open(QIODevice::WriteOnly)) {
		return;
	}
	QDataStream out1(&file1);
	if (out1.status() == QDataStream::Ok) {
		out1 << m_readExpiryList;
	}
	file1.close();
}

void NewsSpot::deserializeObject() {
	// call on app start
	QFile file("./data/ReadUnreadList.dat");
	if (!file.open(QIODevice::ReadOnly)) {
		return;
	}
	QDataStream in(&file);
	if (in.status() == QDataStream::Ok) {
		in >> m_readStatusList;
	}
	file.close();

	QFile file1("./data/ReadExpiryList.dat");
	if (!file1.open(QIODevice::ReadOnly)) {
		return;
	}
	QDataStream in1(&file1);
	if (in1.status() == QDataStream::Ok) {
		in1 >> m_readExpiryList;
	}
	file1.close();
}

void NewsSpot::houseKeepReadStatus() {
	// remove read status from QHash map that is older that 60 days
	QHashIterator<QString, QVariant> iterator(m_readExpiryList);
	QStringList removalKeysList;
	QDateTime maxExpiry = QDateTime::currentDateTime().addDays(-150);
	while (iterator.hasNext()) {
		iterator.next();
		QVariant readTime = iterator.value();
		if (readTime.canConvert<QDateTime>()) {
			if (maxExpiry > readTime.toDateTime()) {
				removalKeysList.append(iterator.key());
			}
		}
	}
	foreach (QString key, removalKeysList) {
		m_readStatusList.remove(key);
		m_readExpiryList.remove(key);
	}
}

void NewsSpot::onExit() {
	serializeObject();
}


text:
#define C_KINO_ARCHITECTURE
#include "KinoSearch/Util/ToolSet.h"

#include "KinoSearch/Plan/Architecture.h"
#include "KinoSearch/Index/DeletionsReader.h"
#include "KinoSearch/Index/DeletionsWriter.h"
#include "KinoSearch/Index/DocReader.h"
#include "KinoSearch/Index/DocWriter.h"
#include "KinoSearch/Index/HighlightReader.h"
#include "KinoSearch/Index/HighlightWriter.h"
#include "KinoSearch/Index/LexiconReader.h"
#include "KinoSearch/Index/LexiconWriter.h"
#include "KinoSearch/Index/PolyReader.h"
#include "KinoSearch/Index/PostingListReader.h"
#include "KinoSearch/Index/PostingListWriter.h"
#include "KinoSearch/Index/Segment.h"
#include "KinoSearch/Index/SegReader.h"
#include "KinoSearch/Index/SegWriter.h"
#include "KinoSearch/Index/Similarity.h"
#include "KinoSearch/Index/Snapshot.h"
#include "KinoSearch/Index/SortReader.h"
#include "KinoSearch/Index/SortWriter.h"
#include "KinoSearch/Plan/Schema.h"
#include "KinoSearch/Store/Folder.h"

Architecture*
Arch_new()
{
    Architecture *self = (Architecture*)VTable_Make_Obj(ARCHITECTURE);
    return Arch_init(self);
}

Architecture*
Arch_init(Architecture *self)
{
    return self;
}

bool_t
Arch_equals(Architecture *self, Obj *other)
{
    Architecture *evil_twin = (Architecture*)other;
    if (evil_twin == self) return true;
    if (!Obj_Is_A(other, ARCHITECTURE)) return false;
    return true;
}

void
Arch_init_seg_writer(Architecture *self, SegWriter *writer)
{
    Arch_Register_Lexicon_Writer(self, writer);
    Arch_Register_Posting_List_Writer(self, writer);
    Arch_Register_Sort_Writer(self, writer);
    Arch_Register_Doc_Writer(self, writer);
    Arch_Register_Highlight_Writer(self, writer);
    Arch_Register_Deletions_Writer(self, writer);
}

void
Arch_register_lexicon_writer(Architecture *self, SegWriter *writer)
{
    Schema        *schema     = SegWriter_Get_Schema(writer);
    Snapshot      *snapshot   = SegWriter_Get_Snapshot(writer);
    Segment       *segment    = SegWriter_Get_Segment(writer);
    PolyReader    *polyreader = SegWriter_Get_PolyReader(writer);
    LexiconWriter *lex_writer
        = LexWriter_new(schema, snapshot, segment, polyreader);
    UNUSED_VAR(self);
    SegWriter_Register(writer, VTable_Get_Name(LEXICONWRITER),
        (DataWriter*)lex_writer);
}

void
Arch_register_posting_list_writer(Architecture *self, SegWriter *writer)
{
    Schema        *schema     = SegWriter_Get_Schema(writer);
    Snapshot      *snapshot   = SegWriter_Get_Snapshot(writer);
    Segment       *segment    = SegWriter_Get_Segment(writer);
    PolyReader    *polyreader = SegWriter_Get_PolyReader(writer);
    LexiconWriter *lex_writer = (LexiconWriter*)SegWriter_Fetch(writer,
        VTable_Get_Name(LEXICONWRITER));
    UNUSED_VAR(self);
    if (!lex_writer) {
        THROW(ERR, "Can't fetch a LexiconWriter");
    }
    else {
        PostingListWriter *plist_writer = PListWriter_new(schema, snapshot,
            segment, polyreader, lex_writer);
        SegWriter_Register(writer, VTable_Get_Name(POSTINGLISTWRITER),
            (DataWriter*)plist_writer);
        SegWriter_Add_Writer(writer, (DataWriter*)INCREF(plist_writer));
    }
}

void
Arch_register_doc_writer(Architecture *self, SegWriter *writer)
{
    Schema     *schema     = SegWriter_Get_Schema(writer);
    Snapshot   *snapshot   = SegWriter_Get_Snapshot(writer);
    Segment    *segment    = SegWriter_Get_Segment(writer);
    PolyReader *polyreader = SegWriter_Get_PolyReader(writer);
    DocWriter  *doc_writer
        = DocWriter_new(schema, snapshot, segment, polyreader);
    UNUSED_VAR(self);
    SegWriter_Register(writer, VTable_Get_Name(DOCWRITER),
        (DataWriter*)doc_writer);
    SegWriter_Add_Writer(writer, (DataWriter*)INCREF(doc_writer));
}

void
Arch_register_sort_writer(Architecture *self, SegWriter *writer)
{
    Schema     *schema     = SegWriter_Get_Schema(writer);
    Snapshot   *snapshot   = SegWriter_Get_Snapshot(writer);
    Segment    *segment    = SegWriter_Get_Segment(writer);
    PolyReader *polyreader = SegWriter_Get_PolyReader(writer);
    SortWriter *sort_writer
        = SortWriter_new(schema, snapshot, segment, polyreader);
    UNUSED_VAR(self);
    SegWriter_Register(writer, VTable_Get_Name(SORTWRITER),
        (DataWriter*)sort_writer);
    SegWriter_Add_Writer(writer, (DataWriter*)INCREF(sort_writer));
}

void
Arch_register_highlight_writer(Architecture *self, SegWriter *writer)
{
    Schema     *schema     = SegWriter_Get_Schema(writer);
    Snapshot   *snapshot   = SegWriter_Get_Snapshot(writer);
    Segment    *segment    = SegWriter_Get_Segment(writer);
    PolyReader *polyreader = SegWriter_Get_PolyReader(writer);
    HighlightWriter *hl_writer
        = HLWriter_new(schema, snapshot, segment, polyreader);
    UNUSED_VAR(self);
    SegWriter_Register(writer, VTable_Get_Name(HIGHLIGHTWRITER),
        (DataWriter*)hl_writer);
    SegWriter_Add_Writer(writer, (DataWriter*)INCREF(hl_writer));
}

void
Arch_register_deletions_writer(Architecture *self, SegWriter *writer)
{
    Schema     *schema     = SegWriter_Get_Schema(writer);
    Snapshot   *snapshot   = SegWriter_Get_Snapshot(writer);
    Segment    *segment    = SegWriter_Get_Segment(writer);
    PolyReader *polyreader = SegWriter_Get_PolyReader(writer);
    DefaultDeletionsWriter *del_writer
        = DefDelWriter_new(schema, snapshot, segment, polyreader);
    UNUSED_VAR(self);
    SegWriter_Register(writer, VTable_Get_Name(DELETIONSWRITER),
        (DataWriter*)del_writer);
    SegWriter_Set_Del_Writer(writer, (DeletionsWriter*)del_writer);
}

void
Arch_init_seg_reader(Architecture *self, SegReader *reader)
{
    Arch_Register_Doc_Reader(self, reader);
    Arch_Register_Lexicon_Reader(self, reader);
    Arch_Register_Posting_List_Reader(self, reader);
    Arch_Register_Sort_Reader(self, reader);
    Arch_Register_Highlight_Reader(self, reader);
    Arch_Register_Deletions_Reader(self, reader);
}

void
Arch_register_doc_reader(Architecture *self, SegReader *reader)
{
    Schema     *schema   = SegReader_Get_Schema(reader);
    Folder     *folder   = SegReader_Get_Folder(reader);
    VArray     *segments = SegReader_Get_Segments(reader);
    Snapshot   *snapshot = SegReader_Get_Snapshot(reader);
    int32_t     seg_tick = SegReader_Get_Seg_Tick(reader);
    DefaultDocReader *doc_reader
        = DefDocReader_new(schema, folder, snapshot, segments, seg_tick);
    UNUSED_VAR(self);
    SegReader_Register(reader, VTable_Get_Name(DOCREADER),
        (DataReader*)doc_reader);
}

void
Arch_register_posting_list_reader(Architecture *self, SegReader *reader)
{
    Schema    *schema   = SegReader_Get_Schema(reader);
    Folder    *folder   = SegReader_Get_Folder(reader);
    VArray    *segments = SegReader_Get_Segments(reader);
    Snapshot  *snapshot = SegReader_Get_Snapshot(reader);
    int32_t    seg_tick = SegReader_Get_Seg_Tick(reader);
    LexiconReader *lex_reader = (LexiconReader*)SegReader_Obtain(reader,
        VTable_Get_Name(LEXICONREADER));
    DefaultPostingListReader *plist_reader = DefPListReader_new(schema, folder,
        snapshot, segments, seg_tick, lex_reader);
    UNUSED_VAR(self);
    SegReader_Register(reader, VTable_Get_Name(POSTINGLISTREADER),
        (DataReader*)plist_reader);
}

void
Arch_register_lexicon_reader(Architecture *self, SegReader *reader)
{
    Schema    *schema   = SegReader_Get_Schema(reader);
    Folder    *folder   = SegReader_Get_Folder(reader);
    VArray    *segments = SegReader_Get_Segments(reader);
    Snapshot  *snapshot = SegReader_Get_Snapshot(reader);
    int32_t    seg_tick = SegReader_Get_Seg_Tick(reader);
    DefaultLexiconReader *lex_reader
        = DefLexReader_new(schema, folder, snapshot, segments, seg_tick);
    UNUSED_VAR(self);
    SegReader_Register(reader, VTable_Get_Name(LEXICONREADER),
        (DataReader*)lex_reader);
}

void
Arch_register_sort_reader(Architecture *self, SegReader *reader)
{
    Schema     *schema   = SegReader_Get_Schema(reader);
    Folder     *folder   = SegReader_Get_Folder(reader);
    VArray     *segments = SegReader_Get_Segments(reader);
    Snapshot   *snapshot = SegReader_Get_Snapshot(reader);
    int32_t     seg_tick = SegReader_Get_Seg_Tick(reader);
    DefaultSortReader *sort_reader
        = DefSortReader_new(schema, folder, snapshot, segments, seg_tick);
    UNUSED_VAR(self);
    SegReader_Register(reader, VTable_Get_Name(SORTREADER),
        (DataReader*)sort_reader);
}

void
Arch_register_highlight_reader(Architecture *self, SegReader *reader)
{
    Schema     *schema   = SegReader_Get_Schema(reader);
    Folder     *folder   = SegReader_Get_Folder(reader);
    VArray     *segments = SegReader_Get_Segments(reader);
    Snapshot   *snapshot = SegReader_Get_Snapshot(reader);
    int32_t     seg_tick = SegReader_Get_Seg_Tick(reader);
    DefaultHighlightReader* hl_reader
        = DefHLReader_new(schema, folder, snapshot, segments, seg_tick);
    UNUSED_VAR(self);
    SegReader_Register(reader, VTable_Get_Name(HIGHLIGHTREADER),
        (DataReader*)hl_reader);
}

void
Arch_register_deletions_reader(Architecture *self, SegReader *reader)
{
    Schema     *schema   = SegReader_Get_Schema(reader);
    Folder     *folder   = SegReader_Get_Folder(reader);
    VArray     *segments = SegReader_Get_Segments(reader);
    Snapshot   *snapshot = SegReader_Get_Snapshot(reader);
    int32_t     seg_tick = SegReader_Get_Seg_Tick(reader);
    DefaultDeletionsReader* del_reader
        = DefDelReader_new(schema, folder, snapshot, segments, seg_tick);
    UNUSED_VAR(self);
    SegReader_Register(reader, VTable_Get_Name(DELETIONSREADER),
        (DataReader*)del_reader);
}

Similarity*
Arch_make_similarity(Architecture *self)
{
    UNUSED_VAR(self);
    return Sim_new();
}

int32_t
Arch_index_interval(Architecture *self)
{
    UNUSED_VAR(self);
    return 128;
}

int32_t
Arch_skip_interval(Architecture *self)
{
    UNUSED_VAR(self);
    return 16;
}


text:
package de.fxnn.brainfuckongenetics.job;

import java.util.Date;
import java.util.concurrent.ExecutionException;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import de.fxnn.brainfuck.program.Program;
import de.fxnn.brainfuckongenetics.BrainfuckOnGeneticsAlgorithmFactory;
import de.fxnn.brainfuckongenetics.BrainfuckOnGeneticsConfiguration;
import de.fxnn.genetics.GeneticAlgorithm;
import de.fxnn.genetics.generation.Generation;
import lombok.Getter;

public class BrainfuckOnGeneticsJob {

  private final BrainfuckOnGeneticsAlgorithmFactory algorithmFactory;

  private ListenableFuture<Generation<Program>> future;

  @Getter
  private Date timestampStarted;

  @Getter
  private volatile Date timestampDone;

  public BrainfuckOnGeneticsJob() {
    algorithmFactory = new BrainfuckOnGeneticsAlgorithmFactory();
  }

  public void start(BrainfuckOnGeneticsConfiguration configuration) throws JobCurrentlyRunningException {
    if (isJobRunning()) {
      throw new JobCurrentlyRunningException(timestampStarted);
    }

    ListeningExecutorService geneticAlgorithmExecutorService = configuration.getGeneticAlgorithmExecutorService();
    GeneticAlgorithm<Program> geneticAlgorithm = algorithmFactory.createGeneticAlgorithm(configuration);

    startClock();
    future = geneticAlgorithmExecutorService.submit(geneticAlgorithm);
    future.addListener(this::stopClock, MoreExecutors.directExecutor());
  }

  public void waitForCompletion() throws NoJobActiveException, InterruptedException, JobExecutionException {
    if (!isJobRunning()) {
      throw new NoJobActiveException();
    }

    try {
      future.get();
    } catch (ExecutionException e) {
      throw new JobExecutionException("The job execution was cancelled with an error: " + e.getCause().toString(), e);
    }
  }

  protected void startClock() {
    timestampDone = null;
    timestampStarted = new Date();
  }

  protected void stopClock() {
    timestampDone = new Date();
  }

  public void cancel() throws NoJobActiveException {
    if (!isJobRunning()) {
      throw new NoJobActiveException();
    }

    stopClock();
    future.cancel(true);
  }

  public Generation<Program> getLastResult()
      throws NoJobActiveException, JobCurrentlyRunningException, JobExecutionException {
    if (future == null) {
      throw new NoJobActiveException();
    }
    if (isJobRunning()) {
      throw new JobCurrentlyRunningException(timestampStarted);
    }

    try {
      return future.get();
    } catch (InterruptedException e) {
      throw new RuntimeException("Could not retrieve job result, as I was interrupted.", e);
    } catch (ExecutionException e) {
      throw new JobExecutionException("The job execution was cancelled with an error: " + e.getCause().toString(), e);
    }
  }

  public long getJobRunDurationInMilliseconds() {
    if (timestampStarted == null) {
      return 0;
    }

    if (timestampDone == null) {
      return new Date().getTime() - getTimestampStarted().getTime();
    }

    return getTimestampDone().getTime() - getTimestampStarted().getTime();
  }

  public boolean isJobRunning() {
    return future != null && !future.isDone();
  }
}


text:
using System;
using System.Xml.Serialization;

namespace EZOper.NetSiteUtilities.AopApi
{
    /// <summary>
    /// AlipayEcoCplifeBillSyncResponse.
    /// </summary>
    public class AlipayEcoCplifeBillSyncResponse : AopResponse
    {
    }
}


text:
package org.action;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.model.Bigboard;
import org.model.Smallboard;
import org.util.HibernateSessionFactory;

import com.opensymphony.xwork2.ActionSupport;

public class AddModule extends ActionSupport{
	private int biboid;
	private String smbotitle;
	public int getBiboid() {
		return biboid;
	}
	public void setBiboid(int biboid) {
		this.biboid = biboid;
	}
	public String getSmbotitle() {
		return smbotitle;
	}
	public void setSmbotitle(String smbotitle) {
		this.smbotitle = smbotitle;
	}
	@Override
	public String execute() throws Exception {
		Session session = HibernateSessionFactory.getSession();
		try {
			Transaction trans = session.beginTransaction();
			Smallboard sb = new Smallboard();
			Bigboard bb = new Bigboard();
			bb.setBiBoid(getBiboid());
			sb.setBigboard(bb);
			sb.setSmBoTitle(getSmbotitle());
			Query lastSmBoIdQuery = session.createQuery("from Smallboard order by smboidid desc");
			lastSmBoIdQuery.setFirstResult(0);
			lastSmBoIdQuery.setMaxResults(1);
			Smallboard theSB = (Smallboard) lastSmBoIdQuery.list().get(0);
			int smboidid = theSB.getSmBoidid() + 1;
			sb.setSmBoidid(smboidid);
			session.save(sb);
			trans.commit();
		} catch(Exception e) {
			e.printStackTrace();
			return ERROR;
		} finally {
			session.close();
		}
		return SUCCESS;
	}
}


text:
package com.elmakers.mine.bukkit.utility.platform.v1_11;

import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;

import com.elmakers.mine.bukkit.api.magic.MageController;
import com.elmakers.mine.bukkit.entity.EntityExtraData;
import com.elmakers.mine.bukkit.utility.platform.Platform;
import com.elmakers.mine.bukkit.utility.platform.v1_11.entity.EntityHorseData;
import com.elmakers.mine.bukkit.utility.platform.v1_11.entity.EntityLlamaData;
import com.elmakers.mine.bukkit.utility.platform.v1_11.entity.EntityMuleData;
import com.elmakers.mine.bukkit.utility.platform.v1_11.entity.EntityZombieVillagerData;

public class EntityUtils extends com.elmakers.mine.bukkit.utility.platform.legacy.EntityUtils  {
    public EntityUtils(final Platform platform) {
        super(platform);
    }

    @Override
    public EntityExtraData getExtraData(MageController controller, Entity entity) {
        switch (entity.getType()) {
            case HORSE:
                return new EntityHorseData(entity, controller);
            case LLAMA:
                return new EntityLlamaData(entity, controller);
            case MULE:
                return new EntityMuleData(entity, controller);
            case ZOMBIE_VILLAGER:
                return new EntityZombieVillagerData(entity);
            default:
                return super.getExtraData(controller, entity);
        }
    }

    @Override
    public EntityExtraData getExtraData(MageController controller, EntityType type, ConfigurationSection parameters) {
        switch (type) {
            case HORSE:
                return new EntityHorseData(parameters, controller);
            case MULE:
                return new EntityMuleData(parameters, controller);
            case LLAMA:
                return new EntityLlamaData(parameters, controller);
            case ZOMBIE_VILLAGER:
                return new EntityZombieVillagerData(parameters, controller);
            default:
                return super.getExtraData(controller, type, parameters);
        }
    }
}


text:
<template>
  <require from="./w3.css"></require>
  <require from="font-awesome/css/font-awesome.css"></require>
  <require from="components/sharedheader"></require>
  <require from="components/sharedfooter.html"></require>

  <sharedheader router.bind="router"></sharedheader>
  <router-view></router-view>
  <sharedfooter></sharedfooter>

</template>


text:
title: Lead Student Technician
company: Information Technology Services–Classroom Hotline
location: UNC-Chapel Hill
start_date: 2016-02-01
end_date: present
---

- Work with the classroom technology team to support 250 multimedia classrooms.
- Train student employees and delegate tasks to them.
- Provide remote and on-site support to faculty, promptly resolving issues.
- Regularly upgrade and install new equipment.
- Use NetLinx Studio to upgrade device firmware.
- Learn the nuances of AMX conference room suite.


text:
<?php
/**
 * Script to export Reportbacks that do not have a corresponding Signup from drupal into Rogue.
 *
 * to run:
 * drush --script-path=../scripts/ php-script export-signupless-reportbacks-to-rogue.php
 */

// Get all the signupless reportbacks
$reportbacks = db_query("SELECT rb.rbid, rb.nid, rb.run_nid, rb.quantity, rb.why_participated, rb.rbid, rb.flagged, rb.uid, rb.created
  FROM dosomething.dosomething_reportback rb
  LEFT JOIN dosomething.dosomething_signup ds on rb.uid = ds.uid AND rb.run_nid = ds.run_nid
  WHERE ds.sid IS NULL
  AND rb.rbid NOT IN (SELECT rbid from dosomething_rogue_reportbacks)");

$client = dosomething_rogue_client();

if (!$reportbacks) {
  echo 'Nothing to migrate!';
}

// For each reportback, send a request for each reportback file to POST /posts and Rogue will automatically create the signup
foreach ($reportbacks as $reportback) {
  echo 'On rbid ' . $reportback->rbid . '...' . PHP_EOL;
  $sent_at = date('Y-m-d H:i:s');

  // Try to get Northstar ID
  $northstar_id = dosomething_user_get_northstar_id($reportback->uid, 'drupal_id');

  if (!$northstar_id) {
    echo "\t" . 'No northstar id, that is terrible ' . $reportback->rbid . PHP_EOL;

    continue;
  }

  // Get reportback files
  $photos = db_query('SELECT rbf.fid, rbf.remote_addr, rbf.caption, rbf.status, rbf.reviewed, rbf.reviewer, rbf.source, rbf.status, rblog.timestamp
                          FROM dosomething_reportback_file rbf
                          INNER JOIN dosomething_reportback_log rblog ON rbf.fid = substring_index(rblog.files, \',\',-1)
                          WHERE rbf.rbid = '. $reportback->rbid . '
                          AND rbf.fid NOT IN (SELECT fid from dosomething_rogue_reportbacks)
                          GROUP BY rbf.fid')->fetchAll();

  // Just send a signup if there are no photos (there are about 25 of these)
  if (!$photos) {
    echo "\t" . 'Reportback ' . $reportback->rbid . ' has no files, sending just a signup' . PHP_EOL;

    // Match Rogue's timestamp format
    $rb_created_at = date('Y-m-d H:i:s', $reportback->timestamp);

    $data = [
      'northstar_id' => $northstar_id,
      'campaign_id' => $reportback->nid,
      'campaign_run_id' => $reportback->run_nid,
      'created_at' => $rb_created_at,
      'updated_at' => $sent_at,
      'quantity' => $reportback->quantity,
      'why_participated' => $reportback->why_participated,
      'dont_send_to_blink' => true,
    ];

    try {
      // We do not need to worry about keeping track of these because sening them to Rogue multiple times will not create multiple signups
      $response = $client->postSignup($data);

      if ($response) {
        echo "\t\t" . 'Migrated data on reportback ' . $reportback->rbid . ' to Rogue.' . PHP_EOL;
        echo "\t\t\t" . 'Rogue Signup ID: ' . $response['data']['signup_id'] . PHP_EOL;
      }

      // Handle getting a 404
      if (!$response) {
        echo '***ERROR: 404 on reportback ' . $reportback->rbid . PHP_EOL;
      }
    }
    catch (GuzzleHttp\Exception\ServerException $e) {
      // These aren't yet caught by Gateway
      echo '***ERROR: SERVER EXCEPTION on reportback ' . $reportback->rbid . PHP_EOL;
    }
    catch (DoSomething\Gateway\Exceptions\ApiException $e) {
      echo '***ERROR: API EXCEPTION on reportback ' . $reportback->rbid . PHP_EOL;
    }

    continue;
  }

  foreach ($photos as $photo) {
    $data = [];

    echo "\t" . 'Trying fid ' . $photo->fid . '...' . PHP_EOL;

    // Match Rogue's timestamp format
    $photo_created_at = date('Y-m-d H:i:s', $photo->timestamp);

    // We want to print this out so we can tell the data team when to start looking
    echo "\t\t" . 'Sending at approximately ' . $sent_at . PHP_EOL;

    $data = [
      'northstar_id' => $northstar_id,
      'campaign_id' => $reportback->nid,
      'campaign_run_id' => $reportback->run_nid,
      'created_at' => $photo_created_at,
      'updated_at' => $sent_at,
      'quantity' => $reportback->quantity,
      'why_participated' => $reportback->why_participated,
      'caption' => $photo->caption,
      'status' => dosomething_rogue_transform_status($photo->status),
      // This will also be the signup source
      'source' => $photo->source,
      'remote_addr' => $photo->remote_addr,
      'file' => dosomething_helpers_get_data_uri_from_fid($photo->fid),
      'dont_send_to_blink' => true,
    ];

    // Send the request to Rogue
    try {
      $response = $client->postPost($data);
      // Make sure we get a successful response
      if ($response) {
        echo "\t\t" . 'Migrated reportback ' . $reportback->rbid . ' file ' . $photo->fid . ' to Rogue.' . PHP_EOL;
        echo "\t\t\t" . 'Rogue Signup ID: ' . $response['data']['signup_id'] . PHP_EOL;
        echo "\t\t\t" . 'Rogue Post ID: ' . $response['data']['id'] . PHP_EOL;

        // Store reference to reportback so we don't try to send repeats upon further runs of the script
        db_insert('dosomething_rogue_reportbacks')
              ->fields([
                'fid' => $photo->fid,
                'rogue_post_id' => $response['data']['id'],
                'rbid' => $reportback->rbid,
                'rogue_signup_id' => $response['data']['signup_id'],
                'created_at' => REQUEST_TIME,
                ])
              ->execute();

      }
      // Handle getting a 404
      if (!$response) {
        echo '***ERROR: 404 on reportback ' . $reportback->rbid . ' file ' . $photo->fid . PHP_EOL;
      }
    }
    catch (GuzzleHttp\Exception\ServerException $e) {
      // These aren't yet caught by Gateway
      echo '***ERROR: SERVER EXCEPTION on reportback ' . $reportback->rbid . ' file ' . $photo->fid . ' to Rogue.' . PHP_EOL;
    }
    catch (DoSomething\Gateway\Exceptions\ApiException $e) {
      echo '***ERROR: API EXCEPTION on reportback ' . $reportback->rbid . ' file ' . $photo->fid . ' to Rogue.' . PHP_EOL;
    }
  }
}

echo 'All finished!' . PHP_EOL;


text:
@implementation ViewController
{
}

+ (void)Release
{
    //Release
}

//since this is a single-view app, initialize Vulkan during view loading.
-(void) viewDidLoad
{
    [super viewDidLoad];

    //back the view with a layer created by the makeBackingLayer method.
    self.view.wantsLayer = YES;
}

//Resize the window to fit the size of the content as set by the sample code.
-(void) viewWillAppear
{
    [super viewWillAppear];
}

@end


text:
import React from 'react'
import { Flash } from 'components/flash'
import { assert } from 'chai';
import { shallow } from 'enzyme';

describe('<Flash/>', () => {
  it('exists', () => {
    assert(Flash);
  });

  it('renders a flash', () => {
    const content = shallow(
      <Flash
        message='Mensagem do Tipo info'
        type='info'
      />
    );
    assert.equal(content.find('FlashContent').props().message, "Mensagem do Tipo info");
  });
});


text:
/**
 */
package org.tud.inf.st.mbt.scenario.util;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;

import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;

import org.eclipse.emf.ecore.EObject;

import org.tud.inf.st.mbt.core.AbstractModelElement;

import org.tud.inf.st.mbt.features.Feature;
import org.tud.inf.st.mbt.features.IFeature;

import org.tud.inf.st.mbt.scenario.*;

/**
 *
 * The Adapter Factory for the model.
 * It provides an adapter createXXX method for each class of the model.
 *
 * @see org.tud.inf.st.mbt.scenario.ScenarioPackage
 * @generated
 */
public class ScenarioAdapterFactory extends AdapterFactoryImpl {
	/**
	 * The cached model package.
	 *
	 *
	 * @generated
	 */
	protected static ScenarioPackage modelPackage;

	/**
	 * Creates an instance of the adapter factory.
	 *
	 *
	 * @generated
	 */
	public ScenarioAdapterFactory() {
		if (modelPackage == null) {
			modelPackage = ScenarioPackage.eINSTANCE;
		}
	}

	/**
	 * Returns whether this factory is applicable for the type of the object.
	 *
	 * This implementation returns true if the object is either the model's package or is an instance object of the model.
	 *
	 * @return whether this factory is applicable for the type of the object.
	 * @generated
	 */
	@Override
	public boolean isFactoryForType(Object object) {
		if (object == modelPackage) {
			return true;
		}
		if (object instanceof EObject) {
			return ((EObject)object).eClass().getEPackage() == modelPackage;
		}
		return false;
	}

	/**
	 * The switch that delegates to the createXXX methods.
	 *
	 *
	 * @generated
	 */
	protected ScenarioSwitch<Adapter> modelSwitch =
		new ScenarioSwitch<Adapter>() {
			@Override
			public Adapter caseScenarioModel(ScenarioModel object) {
				return createScenarioModelAdapter();
			}
			@Override
			public Adapter caseScenarioEntity(ScenarioEntity object) {
				return createScenarioEntityAdapter();
			}
			@Override
			public Adapter caseSpatialBase(SpatialBase object) {
				return createSpatialBaseAdapter();
			}
			@Override
			public Adapter caseScenario(Scenario object) {
				return createScenarioAdapter();
			}
			@Override
			public Adapter casePlacement(Placement object) {
				return createPlacementAdapter();
			}
			@Override
			public Adapter caseAbstractModelElement(AbstractModelElement object) {
				return createAbstractModelElementAdapter();
			}
			@Override
			public Adapter caseIFeature(IFeature object) {
				return createIFeatureAdapter();
			}
			@Override
			public Adapter caseFeature(Feature object) {
				return createFeatureAdapter();
			}
			@Override
			public Adapter defaultCase(EObject object) {
				return createEObjectAdapter();
			}
		};

	/**
	 * Creates an adapter for the target.
	 *
	 *
	 * @param target the object to adapt.
	 * @return the adapter for the target.
	 * @generated
	 */
	@Override
	public Adapter createAdapter(Notifier target) {
		return modelSwitch.doSwitch((EObject)target);
	}

	/**
	 * Creates a new adapter for an object of class '{@link org.tud.inf.st.mbt.scenario.ScenarioModel Model}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see org.tud.inf.st.mbt.scenario.ScenarioModel
	 * @generated
	 */
	public Adapter createScenarioModelAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link org.tud.inf.st.mbt.scenario.ScenarioEntity Entity}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see org.tud.inf.st.mbt.scenario.ScenarioEntity
	 * @generated
	 */
	public Adapter createScenarioEntityAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link org.tud.inf.st.mbt.scenario.SpatialBase Spatial Base}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see org.tud.inf.st.mbt.scenario.SpatialBase
	 * @generated
	 */
	public Adapter createSpatialBaseAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link org.tud.inf.st.mbt.scenario.Scenario Scenario}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see org.tud.inf.st.mbt.scenario.Scenario
	 * @generated
	 */
	public Adapter createScenarioAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link org.tud.inf.st.mbt.scenario.Placement Placement}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see org.tud.inf.st.mbt.scenario.Placement
	 * @generated
	 */
	public Adapter createPlacementAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link org.tud.inf.st.mbt.core.AbstractModelElement Abstract Model Element}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see org.tud.inf.st.mbt.core.AbstractModelElement
	 * @generated
	 */
	public Adapter createAbstractModelElementAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link org.tud.inf.st.mbt.features.IFeature IFeature}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see org.tud.inf.st.mbt.features.IFeature
	 * @generated
	 */
	public Adapter createIFeatureAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for an object of class '{@link org.tud.inf.st.mbt.features.Feature Feature}'.
	 *
	 * This default implementation returns null so that we can easily ignore cases;
	 * it's useful to ignore a case when inheritance will catch all the cases anyway.
	 *
	 * @return the new adapter.
	 * @see org.tud.inf.st.mbt.features.Feature
	 * @generated
	 */
	public Adapter createFeatureAdapter() {
		return null;
	}

	/**
	 * Creates a new adapter for the default case.
	 *
	 * This default implementation returns null.
	 *
	 * @return the new adapter.
	 * @generated
	 */
	public Adapter createEObjectAdapter() {
		return null;
	}

} //ScenarioAdapterFactory


text:
Configure Other JTAG Interfaces
===============================
:link_to_translation:`zh_CN:[中文]`

For guidance about which JTAG interface to select when using OpenOCD with {IDF_TARGET_NAME}, refer to the section :ref:`jtag-debugging-selecting-jtag-adapter`. Then follow the configuration steps below to get it working.

.. only:: SOC_USB_SERIAL_JTAG_SUPPORTED and not esp32c3

    Configure eFuses
    ^^^^^^^^^^^^^^^^

    By default, {IDF_TARGET_NAME} JTAG interface is connected to the :doc:`built-in USB_SERIAL_JTAG peripheral <configure-builtin-jtag>`. To use an external JTAG adapter instead, you need to switch the JTAG interface to the GPIO pins. This can be done by burning eFuses using ``espefuse.py`` tool.

    - Burning ``DIS_USB_JTAG`` eFuse will permanently disable the connection between USB_SERIAL_JTAG and the JTAG port of the CPU. JTAG interface can then be connected to |jtag-gpio-list|. Note that USB CDC functionality of USB_SERIAL_JTAG will still be usable, i.e., flashing and monitoring over USB CDC will still work.
    - Burning ``STRAP_JTAG_SEL`` eFuse will enable selection of JTAG interface by a strapping pin, |jtag-sel-gpio|. If the strapping pin is low when {IDF_TARGET_NAME} is reset, JTAG interface will use |jtag-gpio-list|. If the strapping pin is high, USB_SERIAL_JTAG will be used as the JTAG interface.

    .. warning::
        Burning eFuses is an irreversible operation, so please consider the above options before starting the process.

.. only:: esp32c3

    Configure eFuses
    ^^^^^^^^^^^^^^^^

    By default, {IDF_TARGET_NAME} JTAG interface is connected to the :doc:`built-in USB_SERIAL_JTAG peripheral <configure-builtin-jtag>`. To use an external JTAG adapter instead, you need to switch the JTAG interface to the GPIO pins. This can be done by burning eFuses using ``espefuse.py`` tool.

    Burning ``DIS_USB_JTAG`` eFuse will permanently disable the connection between USB_SERIAL_JTAG and the JTAG port of the CPU. JTAG interface can then be connected to |jtag-gpio-list|. Note that USB CDC functionality of USB_SERIAL_JTAG will still be usable, i.e., flashing and monitoring over USB CDC will still work.

    .. warning::
        Burning eFuses is an irreversible operation, so please consider the above option before starting the process.

Configure Hardware
^^^^^^^^^^^^^^^^^^

1.  Identify all pins/signals on JTAG interface and {IDF_TARGET_NAME} board that should be connected to establish communication.

    .. include:: {IDF_TARGET_PATH_NAME}.inc
        :start-after: jtag-pins
        :end-before: ---

2.  Verify if {IDF_TARGET_NAME} pins used for JTAG communication are not connected to some other hardware that may disturb JTAG operation.

3.  Connect identified pin/signals of {IDF_TARGET_NAME} and JTAG interface.

Configure Drivers
^^^^^^^^^^^^^^^^^

You may need to install driver software to make JTAG work with computer. Refer to documentation of your JTAG adapter for related details.

Connect
^^^^^^^

Connect JTAG interface to the computer. Power on {IDF_TARGET_NAME} and JTAG interface boards. Check if the JTAG interface is visible on the computer.

To carry on with debugging environment setup, proceed to section :ref:`jtag-debugging-run-openocd`.


text:
layout: page
title: Terra Sky Inc. Seminar
date: 2016-05-24
author: Dennis Gutierrez
tags: weekly links, java
status: published
summary: Nullam eget lorem sed nisl ullamcorper ullamcorper.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 06/19/2016
  endDate: 06/24/2016
  ctyhocn: ATYSDHX
  groupCode: TSIS
published: true
---
Nunc egestas libero libero, vitae ullamcorper ex egestas in. Curabitur enim ante, porttitor ut dui non, consequat tincidunt tortor. Aliquam eget ligula fermentum, accumsan elit sit amet, luctus eros. Curabitur eu nisi nec metus cursus interdum a in odio. Duis a augue fermentum, porttitor diam ac, euismod metus. Maecenas justo sapien, accumsan nec pharetra in, cursus sit amet ante. Proin porta neque vel nunc pellentesque auctor. Morbi sit amet ornare eros. Maecenas sed consectetur eros. Etiam a pretium dolor. In hac habitasse platea dictumst. Donec iaculis nibh libero, eget accumsan purus aliquam egestas. Integer purus elit, euismod a gravida quis, dictum sed justo.

* Maecenas quis eros a nunc aliquet dapibus
* Ut vestibulum dui vel erat sodales consectetur.

Ut nec risus tortor. Fusce eu lacus quis augue lacinia egestas at eu arcu. Aliquam tristique, arcu sit amet feugiat viverra, enim metus dapibus est, a gravida purus ligula vitae massa. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam ac risus non sapien euismod ultrices. In hac habitasse platea dictumst. Suspendisse gravida maximus velit non elementum. Duis augue magna, eleifend sit amet urna et, tincidunt pulvinar erat. Etiam et odio a nibh pretium interdum. Maecenas eget luctus sem, id sagittis neque. Aenean placerat mauris ac sem scelerisque, sit amet fermentum est pulvinar. Sed eget orci quam. Donec accumsan erat in arcu rutrum aliquam. Morbi quam velit, hendrerit sed ipsum eu, sollicitudin dapibus nisi. Maecenas consequat sem ac orci semper rutrum.


text:
class Singleton (object):
    instance = None
    def __new__(cls, *args, **kargs):
        if cls.instance is None:
            cls.instance = object.__new__(cls, *args, **kargs)
        return cls.instance

"""definimos el objecto"""

MySingletonUno = Singleton()
MySingletonDos = Singleton()

MySingletonUno.nuevo = "hola"
print MySingletonDos.nuevo

"""Creamos otra instancia del mismo objecto, que almacena la variable nuevo"""

NuevoSingleton = Singleton()
print NuevoSingleton.nuevo


text:
var searchData=
[
  ['elloborate',['elloborate',['../group___reverse-_transform.html#gad71800455c486b350261bdf555d2dd02',1,'elloborate(output_map_letter *letter, output_map_index *index): odsatransform.c'],['../group___reverse-_transform.html#gad71800455c486b350261bdf555d2dd02',1,'elloborate(output_map_letter *letter, output_map_index *index): odsatransform.c']]]
];