text:
using System;
using System.Reflection;

namespace NUnit.Framework.Internal
{
    /// <summary>
    /// AssemblyHelper provides static methods for working
    /// with assemblies.
    /// </summary>
    public class AssemblyHelper
    {
        #region GetAssemblyPath

        /// <summary>
        /// Gets the path from which an assembly was loaded.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <returns>The path.</returns>
        public static string GetAssemblyPath(Assembly assembly)
        {
            string path = assembly.CodeBase;
            Uri uri = new Uri(path);

            // If it wasn't loaded locally, use the Location
            if (!uri.IsFile)
                return assembly.Location;

            if (uri.IsUnc)
                return path.Substring(Uri.UriSchemeFile.Length + 1);

            int start = Uri.UriSchemeFile.Length + Uri.SchemeDelimiter.Length;

            if (path[start] == '/' && path[start + 2] == ':')
                ++start;

            return path.Substring(start);
        }

        #endregion

        #region GetDirectoryName

        /// <summary>
        /// Gets the path to the directory from which an assembly was loaded.
        /// </summary>
        /// <param name="assembly">The assembly.</param>
        /// <returns>The path.</returns>
        public static string GetDirectoryName( Assembly assembly )
        {
            return System.IO.Path.GetDirectoryName(GetAssemblyPath(assembly));
        }

        #endregion
    }
}
#endif


text:
package com.aspose.tasks.examples.Projects;

import com.aspose.tasks.*;
import com.aspose.tasks.Project;
import com.aspose.tasks.examples.Utils;

import java.io.FileInputStream;

public class ReadProjectFiles
{
    public static void main(String[] args) throws Exception
    {
    	// The path to the documents directory.
        String dataDir = Utils.getDataDir(ReadProjectFiles.class);

        CheckIfProjectIsPasswordProtected(dataDir);
        ReadProjectAsTemplate(dataDir);
        ReadProjectFileFromStream(dataDir);
    }

    public static void CheckIfProjectIsPasswordProtected(String dataDir)
    {
    	//ExStart: CheckIfProjectIsPasswordProtected
    	ProjectFileInfo info = Project.getProjectFileInfo(dataDir + "project.mpp");
    	System.out.println("Is file password protected?:" + info.isPasswordProtected());
    	//ExEnd: CheckIfProjectIsPasswordProtected
    }
    public static void ReadProjectAsTemplate(String dataDir)
    {
    	// ExStart: ReadProjectAsTemplate
    	// For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java
    	// Read existing project template file
    	Project project = new Project(dataDir + "ReadProjectFiles.mpt");
    	System.out.println("Name : " + project.get(Prj.NAME));
    	// ExEnd: ReadProjectAsTemplate
    }

    public static void ReadProjectFileFromStream(String dataDir)
    {
    	// ExStart: ReadProjectFiles
    	// For complete examples and data files, please go to https://github.com/aspose-tasks/Aspose.Tasks-for-Java
        try
        {
        	FileInputStream prjStream = new FileInputStream(dataDir + "Project1.mpp");
        	Project existingProject = new Project(prjStream);
        	prjStream.close();

        	System.out.println("Calendar : " + existingProject.get(Prj.NAME));
        }
        catch(Exception ex)
        {
        	System.out.println(ex.getMessage());
        }
        // ExEnd: ReadProjectFiles
        // Display result of conversion.
        System.out.println("Process completed Successfully");
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.kafka.streams.processor.internals;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.InvalidOffsetException;
import org.apache.kafka.clients.consumer.MockConsumer;
import org.apache.kafka.clients.consumer.OffsetResetStrategy;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.TimeoutException;
import org.apache.kafka.common.utils.LogContext;
import org.apache.kafka.common.utils.Utils;
import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.errors.StreamsException;
import org.apache.kafka.streams.processor.StateRestoreListener;
import org.apache.kafka.test.MockRestoreCallback;
import org.apache.kafka.test.MockStateRestoreListener;
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.easymock.Mock;
import org.easymock.MockType;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.time.Duration;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

import static java.util.Arrays.asList;
import static org.apache.kafka.streams.state.internals.RecordConverters.identity;
import static org.apache.kafka.test.MockStateRestoreListener.RESTORE_BATCH;
import static org.apache.kafka.test.MockStateRestoreListener.RESTORE_END;
import static org.apache.kafka.test.MockStateRestoreListener.RESTORE_START;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

@RunWith(EasyMockRunner.class)
public class StoreChangelogReaderTest {

    @Mock(type = MockType.NICE)
    private RestoringTasks active;
    @Mock(type = MockType.NICE)
    private StreamTask task;

    private final MockStateRestoreListener callback = new MockStateRestoreListener();
    private final CompositeRestoreListener restoreListener = new CompositeRestoreListener(callback);
    private final MockConsumer<byte[], byte[]> consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST);
    private final StateRestoreListener stateRestoreListener = new MockStateRestoreListener();
    private final TopicPartition topicPartition = new TopicPartition("topic", 0);
    private final LogContext logContext = new LogContext("test-reader ");
    private final StoreChangelogReader changelogReader = new StoreChangelogReader(
        consumer,
        Duration.ZERO,
        stateRestoreListener,
        logContext);

    @Before
    public void setUp() {
        restoreListener.setUserRestoreListener(stateRestoreListener);
    }

    @Test
    public void shouldRequestTopicsAndHandleTimeoutException() {
        final AtomicBoolean functionCalled = new AtomicBoolean(false);
        final MockConsumer<byte[], byte[]> consumer = new MockConsumer<byte[], byte[]>(OffsetResetStrategy.EARLIEST) {
            @Override
            public Map<String, List<PartitionInfo>> listTopics() {
                functionCalled.set(true);
                throw new TimeoutException("KABOOM!");
            }
        };

        final StoreChangelogReader changelogReader = new StoreChangelogReader(
            consumer,
            Duration.ZERO,
            stateRestoreListener,
            logContext);
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity()));
        changelogReader.restore(active);
        assertTrue(functionCalled.get());
    }

    @Test
    public void shouldThrowExceptionIfConsumerHasCurrentSubscription() {
        final StateRestorer mockRestorer = EasyMock.mock(StateRestorer.class);
        mockRestorer.setUserRestoreListener(stateRestoreListener);
        expect(mockRestorer.partition())
                .andReturn(new TopicPartition("sometopic", 0))
                .andReturn(new TopicPartition("sometopic", 0))
                .andReturn(new TopicPartition("sometopic", 0))
                .andReturn(new TopicPartition("sometopic", 0));
        EasyMock.replay(mockRestorer);
        changelogReader.register(mockRestorer);

        consumer.subscribe(Collections.singleton("sometopic"));

        try {
            changelogReader.restore(active);
            fail("Should have thrown IllegalStateException");
        } catch (final StreamsException expected) {
            // ok
        }
    }

    @Test
    public void shouldRestoreAllMessagesFromBeginningWhenCheckpointNull() {
        final int messages = 10;
        setupConsumer(messages, topicPartition);
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity()));
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);
        changelogReader.restore(active);

        assertThat(callback.restored.size(), equalTo(messages));
    }

    @Test
    public void shouldRecoverFromInvalidOffsetExceptionAndFinishRestore() {
        final int messages = 10;
        setupConsumer(messages, topicPartition);
        consumer.setException(new InvalidOffsetException("Try Again!") {
            @Override
            public Set<TopicPartition> partitions() {
                return Collections.singleton(topicPartition);
            }
        });
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity()));

        EasyMock.expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        EasyMock.replay(active, task);

        // first restore call "fails" but we should not die with an exception
        assertEquals(0, changelogReader.restore(active).size());

        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity()));
        // retry restore should succeed
        assertEquals(1, changelogReader.restore(active).size());
        assertThat(callback.restored.size(), equalTo(messages));
    }

    @Test
    public void shouldRecoverFromOffsetOutOfRangeExceptionAndRestoreFromStart() {
        final int messages = 10;
        final int startOffset = 5;
        final long expiredCheckpoint = 1L;
        assignPartition(messages, topicPartition);
        consumer.updateBeginningOffsets(Collections.singletonMap(topicPartition, (long) startOffset));
        consumer.updateEndOffsets(Collections.singletonMap(topicPartition, (long) (messages + startOffset)));

        addRecords(messages, topicPartition, startOffset);
        consumer.assign(Collections.emptyList());

        final StateRestorer stateRestorer = new StateRestorer(
            topicPartition,
            restoreListener,
            expiredCheckpoint,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity());
        changelogReader.register(stateRestorer);

        EasyMock.expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        EasyMock.replay(active, task);

        // first restore call "fails" since OffsetOutOfRangeException but we should not die with an exception
        assertEquals(0, changelogReader.restore(active).size());
        //the starting offset for stateRestorer is set to NO_CHECKPOINT
        assertThat(stateRestorer.checkpoint(), equalTo(-1L));

        //restore the active task again
        changelogReader.register(stateRestorer);
        //the restored task should return completed partition without Exception.
        assertEquals(1, changelogReader.restore(active).size());
        //the restored size should be equal to message length.
        assertThat(callback.restored.size(), equalTo(messages));
    }

    @Test
    public void shouldRestoreMessagesFromCheckpoint() {
        final int messages = 10;
        setupConsumer(messages, topicPartition);
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            5L,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity()));

        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(5));
    }

    @Test
    public void shouldClearAssignmentAtEndOfRestore() {
        final int messages = 1;
        setupConsumer(messages, topicPartition);
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity()));
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);
        changelogReader.restore(active);
        assertThat(consumer.assignment(), equalTo(Collections.<TopicPartition>emptySet()));
    }

    @Test
    public void shouldRestoreToLimitWhenSupplied() {
        setupConsumer(10, topicPartition);
        final StateRestorer restorer = new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            3,
            true,
            "storeName",
            identity());
        changelogReader.register(restorer);
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);
        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(3));
        assertThat(restorer.restoredOffset(), equalTo(3L));
    }

    @Test
    public void shouldRestoreMultipleStores() {
        final TopicPartition one = new TopicPartition("one", 0);
        final TopicPartition two = new TopicPartition("two", 0);
        final MockRestoreCallback callbackOne = new MockRestoreCallback();
        final MockRestoreCallback callbackTwo = new MockRestoreCallback();
        final CompositeRestoreListener restoreListener1 = new CompositeRestoreListener(callbackOne);
        final CompositeRestoreListener restoreListener2 = new CompositeRestoreListener(callbackTwo);
        setupConsumer(10, topicPartition);
        setupConsumer(5, one);
        setupConsumer(3, two);

        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName1",
            identity()));
        changelogReader.register(new StateRestorer(
            one,
            restoreListener1,
            null,
            Long.MAX_VALUE,
            true,
            "storeName2",
            identity()));
        changelogReader.register(new StateRestorer(
            two,
            restoreListener2,
            null,
            Long.MAX_VALUE,
            true,
            "storeName3",
            identity()));

        expect(active.restoringTaskFor(one)).andStubReturn(task);
        expect(active.restoringTaskFor(two)).andStubReturn(task);
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);
        changelogReader.restore(active);

        assertThat(callback.restored.size(), equalTo(10));
        assertThat(callbackOne.restored.size(), equalTo(5));
        assertThat(callbackTwo.restored.size(), equalTo(3));
    }

    @Test
    public void shouldRestoreAndNotifyMultipleStores() {
        final TopicPartition one = new TopicPartition("one", 0);
        final TopicPartition two = new TopicPartition("two", 0);
        final MockStateRestoreListener callbackOne = new MockStateRestoreListener();
        final MockStateRestoreListener callbackTwo = new MockStateRestoreListener();
        final CompositeRestoreListener restoreListener1 = new CompositeRestoreListener(callbackOne);
        final CompositeRestoreListener restoreListener2 = new CompositeRestoreListener(callbackTwo);
        setupConsumer(10, topicPartition);
        setupConsumer(5, one);
        setupConsumer(3, two);

        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            0L,
            Long.MAX_VALUE,
            true,
            "storeName1",
            identity()));
        changelogReader.register(new StateRestorer(
            one,
            restoreListener1,
            0L,
            Long.MAX_VALUE,
            true,
            "storeName2",
            identity()));
        changelogReader.register(new StateRestorer(
            two,
            restoreListener2,
            0L,
            Long.MAX_VALUE,
            true,
            "storeName3",
            identity()));

        expect(active.restoringTaskFor(one)).andReturn(task);
        expect(active.restoringTaskFor(two)).andReturn(task);
        expect(active.restoringTaskFor(topicPartition)).andReturn(task);
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);
        changelogReader.restore(active);

        changelogReader.restore(active);

        assertThat(callback.restored.size(), equalTo(10));
        assertThat(callbackOne.restored.size(), equalTo(5));
        assertThat(callbackTwo.restored.size(), equalTo(3));

        assertAllCallbackStatesExecuted(callback, "storeName1");
        assertCorrectOffsetsReportedByListener(callback, 0L, 9L, 10L);

        assertAllCallbackStatesExecuted(callbackOne, "storeName2");
        assertCorrectOffsetsReportedByListener(callbackOne, 0L, 4L, 5L);

        assertAllCallbackStatesExecuted(callbackTwo, "storeName3");
        assertCorrectOffsetsReportedByListener(callbackTwo, 0L, 2L, 3L);
    }

    @Test
    public void shouldOnlyReportTheLastRestoredOffset() {
        setupConsumer(10, topicPartition);
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            0L,
            5,
            true,
            "storeName1",
            identity()));
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);
        changelogReader.restore(active);

        assertThat(callback.restored.size(), equalTo(5));
        assertAllCallbackStatesExecuted(callback, "storeName1");
        assertCorrectOffsetsReportedByListener(callback, 0L, 4L, 5L);
    }

    private void assertAllCallbackStatesExecuted(final MockStateRestoreListener restoreListener,
                                                 final String storeName) {
        assertThat(restoreListener.storeNameCalledStates.get(RESTORE_START), equalTo(storeName));
        assertThat(restoreListener.storeNameCalledStates.get(RESTORE_BATCH), equalTo(storeName));
        assertThat(restoreListener.storeNameCalledStates.get(RESTORE_END), equalTo(storeName));
    }

    private void assertCorrectOffsetsReportedByListener(final MockStateRestoreListener restoreListener,
                                                        final long startOffset,
                                                        final long batchOffset,
                                                        final long totalRestored) {

        assertThat(restoreListener.restoreStartOffset, equalTo(startOffset));
        assertThat(restoreListener.restoredBatchOffset, equalTo(batchOffset));
        assertThat(restoreListener.totalNumRestored, equalTo(totalRestored));
    }

    @Test
    public void shouldNotRestoreAnythingWhenPartitionIsEmpty() {
        final StateRestorer restorer = new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity());
        setupConsumer(0, topicPartition);
        changelogReader.register(restorer);

        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(0));
        assertThat(restorer.restoredOffset(), equalTo(0L));
    }

    @Test
    public void shouldNotRestoreAnythingWhenCheckpointAtEndOffset() {
        final long endOffset = 10L;
        setupConsumer(endOffset, topicPartition);
        final StateRestorer restorer = new StateRestorer(
            topicPartition,
            restoreListener,
            endOffset,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity());

        changelogReader.register(restorer);

        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(0));
        assertThat(restorer.restoredOffset(), equalTo(endOffset));
    }

    @Test
    public void shouldReturnRestoredOffsetsForPersistentStores() {
        setupConsumer(10, topicPartition);
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity()));
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);
        changelogReader.restore(active);

        final Map<TopicPartition, Long> restoredOffsets = changelogReader.restoredOffsets();
        assertThat(restoredOffsets, equalTo(Collections.singletonMap(topicPartition, 10L)));
    }

    @Test
    public void shouldNotReturnRestoredOffsetsForNonPersistentStore() {
        setupConsumer(10, topicPartition);
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            false,
            "storeName",
            identity()));
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);
        changelogReader.restore(active);
        final Map<TopicPartition, Long> restoredOffsets = changelogReader.restoredOffsets();
        assertThat(restoredOffsets, equalTo(Collections.emptyMap()));
    }

    @Test
    public void shouldIgnoreNullKeysWhenRestoring() {
        assignPartition(3, topicPartition);
        final byte[] bytes = new byte[0];
        consumer.addRecord(new ConsumerRecord<>(topicPartition.topic(), topicPartition.partition(), 0, bytes, bytes));
        consumer.addRecord(new ConsumerRecord<>(topicPartition.topic(), topicPartition.partition(), 1, null, bytes));
        consumer.addRecord(new ConsumerRecord<>(topicPartition.topic(), topicPartition.partition(), 2, bytes, bytes));
        consumer.assign(Collections.singletonList(topicPartition));
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            false,
            "storeName",
            identity()));
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);
        changelogReader.restore(active);

        assertThat(callback.restored, CoreMatchers.equalTo(asList(KeyValue.pair(bytes, bytes), KeyValue.pair(bytes, bytes))));
    }

    @Test
    public void shouldCompleteImmediatelyWhenEndOffsetIs0() {
        final Collection<TopicPartition> expected = Collections.singleton(topicPartition);
        setupConsumer(0, topicPartition);
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "store",
            identity()));
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        replay(active, task);

        final Collection<TopicPartition> restored = changelogReader.restore(active);
        assertThat(restored, equalTo(expected));
    }

    @Test
    public void shouldRestorePartitionsRegisteredPostInitialization() {
        final MockRestoreCallback callbackTwo = new MockRestoreCallback();
        final CompositeRestoreListener restoreListener2 = new CompositeRestoreListener(callbackTwo);

        setupConsumer(1, topicPartition);
        consumer.updateEndOffsets(Collections.singletonMap(topicPartition, 10L));
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            false,
            "storeName",
            identity()));

        final TopicPartition postInitialization = new TopicPartition("other", 0);
        expect(active.restoringTaskFor(topicPartition)).andStubReturn(task);
        expect(active.restoringTaskFor(postInitialization)).andStubReturn(task);
        replay(active, task);

        assertTrue(changelogReader.restore(active).isEmpty());

        addRecords(9, topicPartition, 1);

        setupConsumer(3, postInitialization);
        consumer.updateBeginningOffsets(Collections.singletonMap(postInitialization, 0L));
        consumer.updateEndOffsets(Collections.singletonMap(postInitialization, 3L));

        changelogReader.register(new StateRestorer(
            postInitialization,
            restoreListener2,
            null,
            Long.MAX_VALUE,
            false,
            "otherStore",
            identity()));

        final Collection<TopicPartition> expected = Utils.mkSet(topicPartition, postInitialization);
        consumer.assign(expected);

        assertThat(changelogReader.restore(active), equalTo(expected));
        assertThat(callback.restored.size(), equalTo(10));
        assertThat(callbackTwo.restored.size(), equalTo(3));
    }

    @Test
    public void shouldNotThrowTaskMigratedExceptionIfSourceTopicUpdatedDuringRestoreProcess() {
        final int messages = 10;
        setupConsumer(messages, topicPartition);
        // in this case first call to endOffsets returns correct value, but a second thread has updated the source topic
        // but since it's a source topic, the second check should not fire hence no exception
        consumer.addEndOffsets(Collections.singletonMap(topicPartition, 15L));
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            9L,
            true,
            "storeName",
            identity()));

        expect(active.restoringTaskFor(topicPartition)).andReturn(task);
        replay(active);

        changelogReader.restore(active);
    }

    @Test
    public void shouldNotThrowTaskMigratedExceptionDuringRestoreForChangelogTopicWhenEndOffsetNotExceededEOSEnabled() {
        final int totalMessages = 10;
        setupConsumer(totalMessages, topicPartition);
        // records have offsets of 0..9 10 is commit marker so 11 is end offset
        consumer.updateEndOffsets(Collections.singletonMap(topicPartition, 11L));

        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity()));

        expect(active.restoringTaskFor(topicPartition)).andReturn(task);
        replay(active);

        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(10));
    }

    @Test
    public void shouldNotThrowTaskMigratedExceptionDuringRestoreForChangelogTopicWhenEndOffsetNotExceededEOSDisabled() {
        final int totalMessages = 10;
        setupConsumer(totalMessages, topicPartition);

        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            Long.MAX_VALUE,
            true,
            "storeName",
            identity()));

        expect(active.restoringTaskFor(topicPartition)).andReturn(task);
        replay(active);

        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(10));
    }

    @Test
    public void shouldNotThrowTaskMigratedExceptionIfEndOffsetGetsExceededDuringRestoreForSourceTopic() {
        final int messages = 10;
        setupConsumer(messages, topicPartition);
        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            5,
            true,
            "storeName",
            identity()));

        expect(active.restoringTaskFor(topicPartition)).andReturn(task);
        replay(active);

        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(5));
    }

    @Test
    public void shouldNotThrowTaskMigratedExceptionIfEndOffsetNotExceededDuringRestoreForSourceTopic() {
        final int messages = 10;
        setupConsumer(messages, topicPartition);

        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            10,
            true,
            "storeName",
            identity()));

        expect(active.restoringTaskFor(topicPartition)).andReturn(task);
        replay(active);

        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(10));
    }

    @Test
    public void shouldNotThrowTaskMigratedExceptionIfEndOffsetGetsExceededDuringRestoreForSourceTopicEOSEnabled() {
        final int totalMessages = 10;
        assignPartition(totalMessages, topicPartition);
        // records 0..4 last offset before commit is 4
        addRecords(5, topicPartition, 0);
        //EOS enabled so commit marker at offset 5 so records start at 6
        addRecords(5, topicPartition, 6);
        consumer.assign(Collections.emptyList());
        // commit marker is 5 so ending offset is 12
        consumer.updateEndOffsets(Collections.singletonMap(topicPartition, 12L));

        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            6,
            true,
            "storeName",
            identity()));

        expect(active.restoringTaskFor(topicPartition)).andReturn(task);
        replay(active);

        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(5));
    }

    @Test
    public void shouldNotThrowTaskMigratedExceptionIfEndOffsetNotExceededDuringRestoreForSourceTopicEOSEnabled() {
        final int totalMessages = 10;
        setupConsumer(totalMessages, topicPartition);
        // records have offsets 0..9 10 is commit marker so 11 is ending offset
        consumer.updateEndOffsets(Collections.singletonMap(topicPartition, 11L));

        changelogReader.register(new StateRestorer(
            topicPartition,
            restoreListener,
            null,
            11,
            true,
            "storeName",
            identity()));

        expect(active.restoringTaskFor(topicPartition)).andReturn(task);
        replay(active);

        changelogReader.restore(active);
        assertThat(callback.restored.size(), equalTo(10));
    }

    private void setupConsumer(final long messages,
                               final TopicPartition topicPartition) {
        assignPartition(messages, topicPartition);
        addRecords(messages, topicPartition, 0);
        consumer.assign(Collections.emptyList());
    }

    private void addRecords(final long messages,
                            final TopicPartition topicPartition,
                            final int startingOffset) {
        for (int i = 0; i < messages; i++) {
            consumer.addRecord(new ConsumerRecord<>(
                topicPartition.topic(),
                topicPartition.partition(),
                startingOffset + i,
                new byte[0],
                new byte[0]));
        }
    }

    private void assignPartition(final long messages,
                                 final TopicPartition topicPartition) {
        consumer.updatePartitions(
            topicPartition.topic(),
            Collections.singletonList(new PartitionInfo(
                topicPartition.topic(),
                topicPartition.partition(),
                null,
                null,
                null)));
        consumer.updateBeginningOffsets(Collections.singletonMap(topicPartition, 0L));
        consumer.updateEndOffsets(Collections.singletonMap(topicPartition, Math.max(0, messages)));
        consumer.assign(Collections.singletonList(topicPartition));
    }

}


text:
Array.prototype.selectMany = function (selector, resSelector) {
	resSelector = resSelector || function (i, res) { return res; };
	return this.aggregate(function (a, b) {
		return a.concat(selector(b).select(function (res) { return resSelector(b, res) }));
	}, []);
};


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Mercado Eletrônico</title>
    <meta name="viewport" content="initial-scale=1.0,user-scalable=no,maximum-scale=1,width=device-width">
    <meta name="viewport" content="initial-scale=1.0,user-scalable=no,maximum-scale=1" media="(device-height: 568px)">
	<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css">


text:
package org.springframework.richclient.form.binding.swing.date;

import java.util.Date;

import javax.swing.JComponent;

import net.sf.nachocalendar.components.DateField;

/**
 * Tests for NachoCalendarDateFieldBinder and NachoCalendarDateFieldBinding
 *
 * @author Peter De Bruycker
 */
public class NachoCalendarDateFieldBinderTests extends AbstractDateFieldBindingTestCase {

	protected AbstractDateFieldBinder createBinder() {
		return new NachoCalendarDateFieldBinder();
	}

	protected Date getValue(JComponent dateField) {
		return (Date) ((DateField) dateField).getValue();
	}

	protected void setValue(JComponent dateField, Date date) {
		((DateField) dateField).setValue(date);
	}

	protected boolean isReadOnly(JComponent dateField) {
		return !dateField.isEnabled();
	}
}


text:
<?php

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

<title>OPD Demo</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url('/Bootstrap/css/bootstrap.css'); ?>" media="all"/>

<link rel="stylesheet" type="text/css" href="<?php echo base_url('/Bootstrap/css/sb-admin.css'); ?>" media="all"/>
<link rel="stylesheet" type="text/css" href="<?php echo base_url('/Bootstrap/font-awesome/css/font-awesome.min.css'); ?>" media="all"/>

            <?php $this->load->view('layout/opd_header'); ?>


text:
WordPress plugin that uses the Backstretch jQuery plugin to add a Backstretch Slideshow via the WordPress Customizer.

## Requirements
 * WordPress 4.0

## Installation

### Upload

1. Download the latest tagged archive (choose the "zip" option).
2. Go to the __Plugins -> Add New__ screen and click the __Upload__ tab.
3. Upload the zipped archive directly.
4. Go to the Plugins screen and click __Activate__.

### Manual

1. Download the latest tagged archive (choose the "zip" option).
2. Unzip the archive.
3. Copy the folder to your `/wp-content/plugins/` directory.
4. Go to the Plugins screen and click __Activate__.

Check out the Codex for more information about [installing plugins manually](http://codex.wordpress.org/Managing_Plugins#Manual_Plugin_Installation).

## Usage

This plugin adds a Backstretch Slideshow of three images via the WordPress Customizer. You can specify the container in which the Backstretch Slideshow will display. You may also specify the Slide Duration, the Fade Duration, the Overlay Color and the Overlay Opacity.

## Issues

This software is considered to be in beta stage and for evaluation use only. Do not use in a production site at this time.

## License

[General Public License (GPL-2.0)](https://www.gnu.org/licenses/gpl-2.0.html)

## Credits

Created by [Brad Potter](https://twitter.com/bradleypotter)
Copyright 2015 [Brad Potter](http://bradpotter.com/)

Some code is inspired by GPL code within the Genesis Framework created by [StudioPress](http://studiopress.com)
Backstretch is an open source MIT Licensed jQuery plugin authored by [Scott Robin](http://srobbin.com/jquery-plugins/backstretch/)


text:
<?php

$__SCOPES = [];
// Saves parent id for each scope id.
$__SCOPE_PARENTS = [];
// $__NONLOCALS = [];

// NOTE: static variables??
// NOTE: references (`&`)??

function __register_scope($scope_id, $parent_scope_id) {
    global $__SCOPES;
    global $__SCOPE_PARENTS;
    // global $__NONLOCALS;
    $__SCOPES[$scope_id] = [];
    $__SCOPE_PARENTS[$scope_id] = $parent_scope_id;
    // $__NONLOCALS[$scope_id] = [];
}

// function __set_nonlocal($scope_id, $varname) {
//     global $__NONLOCALS;
//     $__NONLOCALS[$scope_id][$varname] = True;
// }

// returns a reference to the variable with the given name in the next outer scope where it is defined
function &__lookup_nonlocal($scope_id, $varname) {
    global $__SCOPES;
    global $__SCOPE_PARENTS;
    // NOTE: This should not happen if python has no errors.
    // if (!array_key_exists($__SCOPE_PARENTS[$scope_id], $__SCOPES)) {
    //     throw new Exception('Used nonlocal lookup in global scope.', 1);
    // }
    // echo "nonlocal lookup: ($scope_id, $varname)\n";
    $parent_scope_id = $__SCOPE_PARENTS[$scope_id];
    // echo "parent id = $parent_scope_id\n";
    $parent_scope = &$__SCOPES[$parent_scope_id];
    while ($parent_scope !== null && !array_key_exists($varname, $parent_scope)) {
        $parent_scope_id = $__SCOPE_PARENTS[$parent_scope_id];
        // echo "parent id = $parent_scope_id\n";
        $parent_scope = &$__SCOPES[$parent_scope_id];
    }

    // NOTE: This should not happen if python has no errors.
    // if (!array_key_exists($varname, $parent_scope)) {
    //     throw new Exception('Error during nonlocal lookup.', 1);
    // }
    return $parent_scope[$varname];
}

function __set_var($scope_id, $varname, $value, $nonlocal_lookup=False) {
    global $__SCOPES;
    if (!$nonlocal_lookup) {
        $scope = &$__SCOPES[$scope_id];
        $scope[$varname] = $value;
    }
    else {
        $var = &__lookup_nonlocal($scope_id, $varname);
        $var = $value;
    }
    // echo "__set_var $scope_id $varname\n";
    return $value;
}

function __set_var_nonlocal($scope_id, $varname, $value) {
    return __set_var($scope_id, $varname, $value, True);
}

function &__get_var($scope_id, $varname) {
    global $__SCOPES;
    // defined in local scope
    if (array_key_exists($varname, $__SCOPES[$scope_id])) {
        return $__SCOPES[$scope_id][$varname];
    }
    // defined somewhere outside the local scope
    else {
        return __lookup_nonlocal($scope_id, $varname);
    }
}

// function &__get_var_nonlocal($scope_id, $varname) {
//     return __get_var($scope_id, $varname, True);
// }

__register_scope(0, null);

$a = function() {
    // $__scope_id = uniqid('', True);
    __register_scope(1, 0);

    // $var = 1;
    __set_var(1, 'var', 1);
    __set_var(1, 'b', function() {
        __register_scope(2, 1);
        __set_var(2, 'c', function() {
            __register_scope(3, 2);
            // NONLOCAL: using variable from 2 scopes outside
            __set_var_nonlocal(3, 'var', 4);
        });
        call_user_func(__get_var(2, 'c'));
    });

    // $b = function() {
    //     __register_scope(2, get_defined_vars());
    //     $c = function() {
    //         __register_scope(2, get_defined_vars());
    //         // using variable from 2 scopes outside
    //         // $var = 4;
    //         __set_var(2, 'var', 4);
    //     };
    // };

    // $b();
    call_user_func(__get_var(1, 'b'));
    return __get_var(1, 'var');
};

// $res = $a();
// echo "\nRESULT: ";
// var_dump($res);
// echo "\n";
// var_dump($__SCOPES);

// As a note, get_defined_vars() does not return a set of variable references (as I hoped). For example:
//
//
// // define a variable
// $my_var = "foo";
//
// // get our list of defined variables
// $defined_vars = get_defined_vars();
//
// // now try to change the value through the returned array
// $defined_vars["my_var"] = "bar";
//
// echo $my_var, "\n";
//
//
// will output "foo" (the original value). It'd be nice if get_defined_vars() had an optional argument to make them references, but I imagine its a rather specialized request. You can do it yourself (less conveniently) with something like:
//
//
// $defined_vars = array();
// $var_names = array_keys(get_defined_vars());
//
// foreach ($var_names as $var_name)
// {
//     $defined_vars[$var_name] =& $$var_name;
// }
//


text:
include_directories(${NPP2_SOURCE_DIR}/core)
LIST(APPEND core_srcs
	${NPP2_SOURCE_DIR}/core/BasicLayerTypes.cpp
	${NPP2_SOURCE_DIR}/core/FullyConnectedLayer.cpp
	${NPP2_SOURCE_DIR}/core/functions.cpp
	${NPP2_SOURCE_DIR}/core/npp2.cpp
	${NPP2_SOURCE_DIR}/core/NPPException.cpp
)

LIST(APPEND core_headers
	${NPP2_SOURCE_DIR}/core/BasicLayerTypes.h
	${NPP2_SOURCE_DIR}/core/FullyConnectedLayer.h
	${NPP2_SOURCE_DIR}/core/functions.h
	${NPP2_SOURCE_DIR}/core/npp2.h
	${NPP2_SOURCE_DIR}/core/NPPException.h
)


text:
import collections
import contextlib
import pkg_resources
import sys

import rpm
import tarfile

from anvil import colorizer
from anvil import exceptions as excp
from anvil import log as logging
from anvil.packaging import base
from anvil.packaging.helpers import pip_helper
from anvil.packaging.helpers import yum_helper
from anvil import settings
from anvil import shell as sh
from anvil import utils

LOG = logging.getLogger(__name__)

# Certain versions of pbr seem to miss these files, which causes the rpmbuild
# phases to not complete correctly. Ensure that we don't miss them.
ENSURE_NOT_MISSING = [
    'doc',  # Without this one our rpm doc build won't work
    'README.rst',  # Without this one pbr won't work (thus killing setup.py)
    'babel.cfg',
    'HACKING',
    'AUTHORS',
    'ChangeLog',
    'CONTRIBUTING.rst',
    'LICENSE',
]

class YumInstallHelper(base.InstallHelper):
    def pre_install(self, pkg, params=None):
        """pre-install is handled in openstack-deps %pre script.
        """
        pass

    def post_install(self, pkg, params=None):
        """post-install is handled in openstack-deps %post script.
        """
        pass

class YumDependencyHandler(base.DependencyHandler):
    OPENSTACK_EPOCH = 2
    SPEC_TEMPLATE_DIR = "packaging/specs"
    API_NAMES = {
        "nova": "Compute",
        "glance": "Image",
        "keystone": "Identity",
        "cinder": "Volume",
        "quantum": "Networking",
    }
    SERVER_NAMES = ["nova", "glance", "keystone", "quantum", "cinder"]
    TRANSLATION_NAMES = {
        'horizon': "python-django-horizon",
    }
    REPO_FN = "anvil.repo"
    YUM_REPO_DIR = "/etc/yum.repos.d/"
    BANNED_PACKAGES = [
        'distribute',
        'setuptools',
    ]
    SRC_REPOS = {
        'anvil': 'anvil-source',
        "anvil-deps": "anvil-deps-source",
    }
    REPOS = ["anvil-deps", "anvil"]
    py2rpm_executable = sh.which("py2rpm", ["tools/"])
    rpmbuild_executable = sh.which("rpmbuild")
    jobs = 2

    def __init__(self, distro, root_dir, instances, opts=None):
        super(YumDependencyHandler, self).__init__(distro, root_dir, instances, opts)
        self.rpmbuild_dir = sh.joinpths(self.deps_dir, "rpmbuild")
        self.deps_repo_dir = sh.joinpths(self.deps_dir, "openstack-deps")
        self.deps_src_repo_dir = sh.joinpths(self.deps_dir, "openstack-deps-sources")
        self.anvil_repo_filename = sh.joinpths(self.deps_dir, self.REPO_FN)
        self.helper = yum_helper.Helper()
        self.rpm_sources_dir = sh.joinpths(self.rpmbuild_dir, "SOURCES")
        self.anvil_repo_dir = sh.joinpths(self.root_dir, "repo")
        self._no_remove = None

    def py2rpm_start_cmdline(self):
        cmdline = [
            self.py2rpm_executable,
            "--rpm-base",
            self.rpmbuild_dir,
        ]
        if self.python_names:
            cmdline += [
               "--epoch-map",
            ] + ["%s==%s" % (name, self.OPENSTACK_EPOCH)
                 for name in self.python_names]
        package_map = self.distro._dependency_handler.get("package_map", {})
        if package_map:
            cmdline += [
                "--package-map",
            ] + ["%s==%s" % (key, value)
                 for key, value in package_map.iteritems()]
        arch_dependent = self.distro._dependency_handler.get(
            "arch_dependent", [])
        if arch_dependent:
            cmdline += [
                "--arch-dependent",
            ] + arch_dependent
        return cmdline

    def _package_parameters(self, instance):
        params = {}
        params["release"] = instance.get_option("release", default_value="1")
        if '-' in params["release"]:
            # NOTE(imelnikov): "-" is prohibited in RPM releases
            raise ValueError("Malformed package release: %r" % params["release"])
        version_suffix = instance.get_option("version_suffix", default_value="")
        if version_suffix and not version_suffix.startswith('.'):
            version_suffix = '.' + version_suffix
        params['version_suffix'] = version_suffix
        return params

    def _create_rpmbuild_subdirs(self):
        for dirname in (sh.joinpths(self.rpmbuild_dir, "SPECS"),
                        sh.joinpths(self.rpmbuild_dir, "SOURCES")):
            sh.mkdirslist(dirname, tracewriter=self.tracewriter)

    def package_instance(self, instance):
        with sh.remove_before_after(self.rpmbuild_dir):
            self._create_rpmbuild_subdirs()
            if instance.name in ["general"]:
                self._build_dependencies()
                self._move_srpms("anvil-deps")
            else:
                # Meta packages don't get built.
                app_dir = instance.get_option("app_dir")
                if sh.isdir(app_dir):
                    self._build_openstack_package(instance)
                    self._move_srpms("anvil")

    @staticmethod
    def _move_files(source_dir, target_dir):
        if not sh.isdir(source_dir):
            return
        for filename in sh.listdir(source_dir, recursive=True, files_only=True):
            sh.move(filename, target_dir, force=True)

    def build_binary(self):
        def _is_src_rpm(filename):
            return filename.endswith('.src.rpm')

        LOG.info("Installing build requirements")
        self.helper.transaction(
            install_pkgs=self.requirements["build-requires"],
            tracewriter=self.tracewriter)

        for repo_name in self.REPOS:
            repo_dir = sh.joinpths(self.anvil_repo_dir, repo_name)
            sh.mkdirslist(repo_dir, tracewriter=self.tracewriter)
            src_repo_dir = sh.joinpths(self.anvil_repo_dir, self.SRC_REPOS[repo_name])
            if sh.isdir(src_repo_dir):
                src_repo_files = sh.listdir(src_repo_dir, files_only=True)
                src_repo_files = sorted([f for f in src_repo_files if _is_src_rpm(f)])
            else:
                src_repo_files = []
            if not src_repo_files:
                continue
            LOG.info('Building %s RPM packages from their SRPMs for repo %s using %s jobs',
                     len(src_repo_files), self.SRC_REPOS[repo_name], self.jobs)
            makefile_name = sh.joinpths(self.deps_dir, "binary-%s.mk" % repo_name)
            marks_dir = sh.joinpths(self.deps_dir, "marks-binary")
            sh.mkdirslist(marks_dir, tracewriter=self.tracewriter)
            (_fn, content) = utils.load_template("packaging/makefiles", "binary.mk")
            rpmbuild_flags = ("--rebuild --define '_topdir %s'" % self.rpmbuild_dir)
            if self.opts.get("usr_only", False):
                rpmbuild_flags += "--define 'usr_only 1'"
            params = {
                "SRC_REPO_DIR": src_repo_dir,
                "RPMBUILD_FLAGS": rpmbuild_flags,
                "LOGS_DIR": self.log_dir,
            }
            sh.write_file(makefile_name,
                          utils.expand_template(content, params),
                          tracewriter=self.tracewriter)
            with sh.remove_before_after(self.rpmbuild_dir):
                self._create_rpmbuild_subdirs()
                self._execute_make(makefile_name, marks_dir)
                self._move_files(sh.joinpths(self.rpmbuild_dir, "RPMS"),
                                 repo_dir)
            self._create_repo(repo_name)

    def _execute_make(self, filename, marks_dir):
        sh.execute(
            ["make", "-f", filename, "-j", str(self.jobs)],
            cwd=marks_dir,
            stdout_fh=sys.stdout, stderr_fh=sys.stderr)

    def _move_srpms(self, repo_name):
        src_repo_name = self.SRC_REPOS[repo_name]
        src_repo_dir = sh.joinpths(self.anvil_repo_dir, src_repo_name)
        sh.mkdirslist(src_repo_dir, tracewriter=self.tracewriter)
        self._move_files(sh.joinpths(self.rpmbuild_dir, "SRPMS"), src_repo_dir)

    def _create_repo(self, repo_name):
        repo_dir = sh.joinpths(self.anvil_repo_dir, repo_name)
        src_repo_dir = sh.joinpths(self.anvil_repo_dir, self.SRC_REPOS[repo_name])
        for a_dir in (repo_dir, src_repo_dir):
            if not sh.isdir(a_dir):
                sh.mkdirslist(a_dir, tracewriter=self.tracewriter)
            cmdline = ["createrepo", a_dir]
            LOG.info("Creating repo at %s", a_dir)
            sh.execute(cmdline)
        repo_filename = sh.joinpths(self.anvil_repo_dir, "%s.repo" % repo_name)
        LOG.info("Writing %s", repo_filename)
        (_fn, content) = utils.load_template("packaging", "common.repo")
        params = {
            "repo_name": repo_name,
            "baseurl_bin": "file://%s" % repo_dir,
            "baseurl_src": "file://%s" % src_repo_dir,
        }
        sh.write_file(repo_filename, utils.expand_template(content, params),
                      tracewriter=self.tracewriter)
        # Install *.repo file so that anvil deps will be available
        # when building OpenStack
        system_repo_filename = sh.joinpths(self.YUM_REPO_DIR, "%s.repo" % repo_name)
        sh.copy(repo_filename, system_repo_filename)
        LOG.info("Copying to %s", system_repo_filename)
        self.tracewriter.file_touched(system_repo_filename)

    def _get_yum_available(self):
        yum_map = collections.defaultdict(list)
        for pkg in self.helper.get_available():
            for provides in pkg['provides']:
                yum_map[provides[0]].append((pkg['version'], pkg['repo']))
        return dict(yum_map)

    @staticmethod
    def _find_yum_match(yum_map, req, rpm_name):
        yum_versions = yum_map.get(rpm_name, [])
        for (version, repo) in yum_versions:
            if version in req:
                return (version, repo)
        return (None, None)

    def filter_download_requires(self):
        yum_map = self._get_yum_available()
        pip_origins = {}
        for line in self.pips_to_install:
            req = pip_helper.extract_requirement(line)
            pip_origins[req.key] = line

        pips_to_download = []
        req_to_install = [pip_helper.extract_requirement(line)
                          for line in self.pips_to_install]
        requested_names = [req.key for req in req_to_install]
        rpm_to_install = self._convert_names_python2rpm(requested_names)

        satisfied_list = []
        for (req, rpm_name) in zip(req_to_install, rpm_to_install):
            (version, repo) = self._find_yum_match(yum_map, req, rpm_name)
            if not repo:
                # We need the source requirement incase its a url.
                pips_to_download.append(pip_origins[req.key])
            else:
                satisfied_list.append((req, rpm_name, version, repo))

        if satisfied_list:
            # Organize by repo
            repos = collections.defaultdict(list)
            for (req, rpm_name, version, repo) in satisfied_list:
                repos[repo].append("%s as %s-%s" % (req, rpm_name, version))
            for r in sorted(repos.keys()):
                header = ("%s Python packages are already available "
                          "as RPMs from repository %s")
                header = header % (len(repos[r]), colorizer.quote(r))
                utils.log_iterable(sorted(repos[r]), logger=LOG, header=header)
        return pips_to_download

    def _build_dependencies(self):
        (pips_downloaded, package_files) = self.download_dependencies()

        # Analyze what was downloaded and eject things that were downloaded
        # by pip as a dependency of a download but which we do not want to
        # build or can satisfy by other means
        no_pips = [pkg_resources.Requirement.parse(name).key
                   for name in self.python_names]
        no_pips.extend(self.BANNED_PACKAGES)
        yum_map = self._get_yum_available()
        pips_keys = set([p.key for p in pips_downloaded])

        def _filter_package_files(package_files):
            package_reqs = []
            package_keys = []
            for filename in package_files:
                package_details = pip_helper.get_archive_details(filename)
                package_reqs.append(package_details['req'])
                package_keys.append(package_details['req'].key)
            package_rpm_names = self._convert_names_python2rpm(package_keys)
            filtered_files = []
            for (filename, req, rpm_name) in zip(package_files, package_reqs,
                                                 package_rpm_names):
                if req.key in no_pips:
                    LOG.info(("Dependency %s was downloaded additionally "
                             "but it is disallowed."), colorizer.quote(req))
                    continue
                if req.key in pips_keys:
                    filtered_files.append(filename)
                    continue
                # See if pip tried to download it but we already can satisfy
                # it via yum and avoid building it in the first place...
                (_version, repo) = self._find_yum_match(yum_map, req, rpm_name)
                if not repo:
                    filtered_files.append(filename)
                else:
                    LOG.info(("Dependency %s was downloaded additionally "
                             "but it can be satisfied by %s from repository "
                             "%s instead."), colorizer.quote(req),
                             colorizer.quote(rpm_name),
                             colorizer.quote(repo))
            return filtered_files

        LOG.info("Filtering %s downloaded files.", len(package_files))
        filtered_package_files = _filter_package_files(package_files)
        if not filtered_package_files:
            LOG.info("No SRPM package dependencies to build.")
            return
        for filename in package_files:
            if filename not in filtered_package_files:
                sh.unlink(filename)
        package_files = filtered_package_files
        makefile_name = sh.joinpths(self.deps_dir, "deps.mk")
        marks_dir = sh.joinpths(self.deps_dir, "marks-deps")
        sh.mkdirslist(marks_dir, tracewriter=self.tracewriter)
        (_fn, content) = utils.load_template("packaging/makefiles", "source.mk")
        scripts_dir = sh.abspth(sh.joinpths(settings.TEMPLATE_DIR, "packaging", "scripts"))
        py2rpm_options = self.py2rpm_start_cmdline()[1:] + [
            "--scripts-dir", scripts_dir,
            "--source-only",
            "--rpm-base", self.rpmbuild_dir,
        ]
        params = {
            "DOWNLOADS_DIR": self.download_dir,
            "LOGS_DIR": self.log_dir,
            "PY2RPM": self.py2rpm_executable,
            "PY2RPM_FLAGS": " ".join(py2rpm_options),
        }
        sh.write_file(makefile_name,
                      utils.expand_template(content, params),
                      tracewriter=self.tracewriter)
        LOG.info("Building %s SRPM packages using %s jobs", len(package_files), self.jobs)
        self._execute_make(makefile_name, marks_dir)

    def _write_spec_file(self, instance, rpm_name, template_name, params):
        requires_what = params.get('requires')
        if not requires_what:
            requires_what = []
        requires_python = []
        try:
            requires_python.extend(instance.egg_info['dependencies'])
        except AttributeError:
            pass
        if requires_python:
            requires_what.extend(self._convert_names_python2rpm(requires_python))
        params['requires'] = requires_what
        params["epoch"] = self.OPENSTACK_EPOCH
        content = utils.load_template(self.SPEC_TEMPLATE_DIR, template_name)[1]
        spec_filename = sh.joinpths(self.rpmbuild_dir, "SPECS", "%s.spec" % rpm_name)
        sh.write_file(spec_filename, utils.expand_template(content, params),
                      tracewriter=self.tracewriter)
        return spec_filename

    def _copy_startup_scripts(self, spec_filename):
        common_init_content = utils.load_template("packaging",
                                                  "common.init")[1]
        for src in rpm.spec(spec_filename).sources:
            script = sh.basename(src[0])
            if not (script.endswith(".init")):
                continue
            target_filename = sh.joinpths(self.rpm_sources_dir, script)
            if sh.isfile(target_filename):
                continue
            bin_name = utils.strip_prefix_suffix(script, "openstack-", ".init")
            if bin_name == "quantum-server":
                daemon_args = ("'--config-file=/etc/quantum/plugin.ini"
                               " --config-file=/etc/quantum/quantum.conf'")
            elif bin_name == "quantum-l3-agent":
                daemon_args = ("'--config-file=/etc/quantum/l3_agent.ini"
                               " --config-file=/etc/quantum/quantum.conf'")
            elif bin_name == "quantum-dhcp-agent":
                daemon_args = ("'--config-file=/etc/quantum/dhcp_agent.ini"
                               " --config-file=/etc/quantum/quantum.conf'")
            else:
                daemon_args = ""
            params = {
                "bin": bin_name,
                "package": bin_name.split("-", 1)[0],
                "daemon_args": daemon_args,
            }
            sh.write_file(target_filename,
                          utils.expand_template(common_init_content, params))

    def _copy_sources(self, instance):
        other_sources_dir = sh.joinpths(settings.TEMPLATE_DIR,
                                        "packaging", "sources", instance.name)
        if sh.isdir(other_sources_dir):
            for filename in sh.listdir(other_sources_dir, files_only=True):
                sh.copy(filename, self.rpm_sources_dir)

    def _copy_patches(self, patches):
        for filename in patches:
            sh.copy(filename, self.rpm_sources_dir)

    def _build_from_spec(self, instance, spec_filename, patches=None):
        pkg_dir = instance.get_option('app_dir')
        if sh.isfile(sh.joinpths(pkg_dir, "setup.py")):
            self._write_python_tarball(instance, pkg_dir, ENSURE_NOT_MISSING)
        else:
            self._write_git_tarball(pkg_dir, spec_filename)
        self._copy_sources(instance)
        if patches:
            self._copy_patches(patches)
        self._copy_startup_scripts(spec_filename)
        cmdline = [
            self.rpmbuild_executable,
            "-bs",
            "--define", "_topdir %s" % self.rpmbuild_dir,
            spec_filename,
        ]
        out_filename = sh.joinpths(self.log_dir, "rpmbuild-%s.log" % instance.name)
        sh.execute_save_output(cmdline, out_filename=out_filename, quiet=True)

    def _write_git_tarball(self, pkg_dir, spec_filename):
        cmdline = [
            "rpm",
            "-q",
            "--specfile", spec_filename,
            "--qf", "%{NAME}-%{VERSION}\n"
        ]
        tar_base = sh.execute(cmdline, cwd=pkg_dir)[0].splitlines()[0].strip()
        # git 1.7.1 from RHEL doesn't understand --format=tar.gz
        output_filename = sh.joinpths(self.rpm_sources_dir,
                                      "%s.tar" % tar_base)
        cmdline = [
            "git",
            "archive",
            "--format=tar",
            "--prefix=%s/" % tar_base,
            "--output=%s" % output_filename,
            "HEAD",
        ]
        sh.execute(cmdline, cwd=pkg_dir)
        sh.gzip(output_filename)
        sh.unlink(output_filename)

    def _write_python_tarball(self, instance, pkg_dir, ensure_exists=None):

        def prefix_exists(text, in_what):
            for t in in_what:
                if t.startswith(text):
                    return True
            return False

        pkg_name = instance.egg_info['name']
        version = instance.egg_info['version']
        base_name = "%s-%s" % (pkg_name, version)
        cmdline = [
            sys.executable,
            "setup.py",
            "sdist",
            "--formats=tar",
            "--dist-dir", self.rpm_sources_dir,
        ]
        out_filename = sh.joinpths(self.log_dir, "sdist-%s.log" % (instance.name))
        sh.execute_save_output(cmdline, cwd=pkg_dir, out_filename=out_filename, quiet=True)
        archive_name = sh.joinpths(self.rpm_sources_dir, "%s.tar" % (base_name))
        if ensure_exists:
            with contextlib.closing(tarfile.open(archive_name, 'r')) as tfh:
                tar_entries = [t.path for t in tfh.getmembers()]
            missing_paths = {}
            for path in ensure_exists:
                tar_path = sh.joinpths(base_name, path)
                source_path = sh.joinpths(pkg_dir, path)
                if not prefix_exists(tar_path, tar_entries) and sh.exists(source_path):
                    missing_paths[tar_path] = source_path
            if missing_paths:
                utils.log_iterable(sorted(missing_paths.keys()),
                                   logger=LOG,
                                   header='%s paths were not archived and will now be' % (len(missing_paths)))
                with contextlib.closing(tarfile.open(archive_name, 'a')) as tfh:
                    for (tar_path, source_path) in missing_paths.items():
                        tfh.add(source_path, tar_path)
        sh.gzip(archive_name)
        sh.unlink(archive_name)

    @staticmethod
    def _is_client(instance_name, egg_name):
        for i in [instance_name, egg_name]:
            if i and i.endswith("client"):
                return True
        return False

    def _get_template_and_rpm_name(self, instance):
        rpm_name = None
        template_name = None
        try:
            egg_name = instance.egg_info['name']
            if self._is_client(instance.name, egg_name):
                rpm_name = egg_name
                template_name = "python-commonclient.spec"
            elif instance.name in self.SERVER_NAMES:
                rpm_name = "openstack-%s" % (egg_name)
            else:
                rpm_name = self.TRANSLATION_NAMES.get(instance.name)
        except AttributeError:
            rpm_name = instance.name
            template_name = "%s.spec" % rpm_name
        return (rpm_name, template_name)

    def _build_from_app_dir(self, instance, params):
        app_dir = instance.get_option('app_dir')
        cmdline = self.py2rpm_start_cmdline()
        cmdline.extend(["--source-only"])
        if 'release' in params:
            cmdline.extend(["--release", params["release"]])
        cmdline.extend(["--", app_dir])
        out_filename = sh.joinpths(self.log_dir, "py2rpm-build-%s.log" % (instance.name))
        sh.execute_save_output(cmdline, cwd=app_dir, out_filename=out_filename,
                               quiet=True)

    def _build_openstack_package(self, instance):
        params = self._package_parameters(instance)
        patches = instance.list_patches("package")
        params['patches'] = [sh.basename(fn) for fn in patches]
        (rpm_name, template_name) = self._get_template_and_rpm_name(instance)
        try:
            egg_name = instance.egg_info['name']
            params["version"] = instance.egg_info["version"]
            if self._is_client(instance.name, egg_name):
                client_name = utils.strip_prefix_suffix(egg_name, "python-", "client")
                if not client_name:
                    msg = "Bad client package name %s" % (egg_name)
                    raise excp.PackageException(msg)
                params["clientname"] = client_name
                params["apiname"] = self.API_NAMES.get(client_name,
                                                       client_name.title())
        except AttributeError:
            spec_filename = None
            if template_name:
                spec_filename = sh.joinpths(settings.TEMPLATE_DIR,
                                            self.SPEC_TEMPLATE_DIR,
                                            template_name)
            if not spec_filename or not sh.isfile(spec_filename):
                rpm_name = None
        if rpm_name:
            if not template_name:
                template_name = "%s.spec" % rpm_name
            spec_filename = self._write_spec_file(instance, rpm_name,
                                                  template_name, params)
            self._build_from_spec(instance, spec_filename, patches)
        else:
            self._build_from_app_dir(instance, params)

    def _convert_names_python2rpm(self, python_names):
        if not python_names:
            return []
        cmdline = self.py2rpm_start_cmdline() + ["--convert"] + python_names
        rpm_names = []
        for line in sh.execute(cmdline)[0].splitlines():
            # format is "Requires: rpm-name <=> X"
            if not line.startswith("Requires:"):
                continue
            line = line[len("Requires:"):].strip()
            positions = [line.find(">"), line.find("<"), line.find("=")]
            positions = sorted([p for p in positions if p != -1])
            if positions:
                line = line[0:positions[0]].strip()
            if line and line not in rpm_names:
                rpm_names.append(line)
        return rpm_names

    def _all_rpm_names(self):
        # This file should have all the requirements (including test ones)
        # that we need to install (and which should have been built as rpms
        # in the previous build stages).
        gathered_requires = sh.load_file(self.gathered_requires_filename).splitlines()
        gathered_requires = [line.strip() for line in gathered_requires if line.strip()]
        req_names = []
        for line in gathered_requires:
            req = pip_helper.extract_requirement(line)
            req_names.append(req.key)
        rpm_names = set(self._convert_names_python2rpm(req_names))
        rpm_names |= self.requirements["requires"]
        for inst in self.instances:
            rpm_names |= inst.package_names()
        return list(rpm_names)

    def install(self):
        super(YumDependencyHandler, self).install()
        self.helper.clean()

        # Erase conflicting packages
        remove_pkgs = [pkg_name
                       for pkg_name in self.requirements["conflicts"]
                       if self.helper.is_installed(pkg_name)]
        self.helper.transaction(install_pkgs=self._all_rpm_names(),
                                remove_pkgs=remove_pkgs,
                                tracewriter=self.tracewriter)

    def uninstall(self):
        super(YumDependencyHandler, self).uninstall()
        if self.tracereader.exists():
            remove_pkgs = self.tracereader.packages_installed()
            self.helper.transaction(remove_pkgs=remove_pkgs)


text:
<?php
namespace Modpack\Model\Github;

use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Json;

/**
 * Description of IssueService
 *
 * @author DerOli82 <https://github.com/DerOli82>
 */
class IssueService implements IssueServiceInterface
{
    /**
     * Issue config
     *
     * @var array
     */
    private $_config;

    /**
     * Basic authentication usermane
     *
     * @var string
     */
    private $_user;

    /**
     * Basic authentication token
     *
     * @var string
     */
    private $_token;

    /**
     * @param array $config
     * @param string $user
     * @param string $token
     */
    public function __construct( array $config, $user, $token )
    {
        $this->_config = $config;
        $this->_user = $user;
        $this->_token = $token;
    }

    /**
     * Author name formatter adds prefix and/or suffix
     *
     * @param string $name
     * @return string
     */
    public function formatterAuthorName( $name )
    {
        $prefix = ( isset( $this->_config["name_prefix"] ) ) ? $this->_config["name_prefix"] : "";
        $suffix = ( isset( $this->_config["name_suffix"] ) ) ? $this->_config["name_suffix"] : "";

        return $prefix . $name . $suffix . " ";
    }
    /**********************************************************************
     * Method - Implements RepositoryServiceInterface
     **********************************************************************/

    /**
     * Post an Issue via Github API
     *
     * @param string $repoUrl
     * @param mixed $data
     * @return \Zend\Http\Response
     */
    public function postIssue( $repoUrl, $data )
    {
        $name   = ( isset( $data->name ) ) ? $this->formatterAuthorName( $data->name ): "";
        $client = new Client( $repoUrl, array(
            "sslverifypeer" => false
        ) );
        $client->setEncType( "application/json" );
        $client->setMethod( Request::METHOD_POST );
        $client->setAuth( $this->_user, $this->_token );
        $client->setRawBody( Json::encode( array(
            "title" => $data->title,
            "body" => $name . $data->description
        )));
        return $client->send();
    }
}


text:
package com.seachangesimulations.osp.gametime;

import java.util.Date;
import java.util.Hashtable;

import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Transient;
import javax.servlet.http.HttpServletRequest;

import org.usip.osp.networking.SessionObjectBase;
import org.usip.osp.networking.USIP_OSP_Cache;
import org.usip.osp.networking.USIP_OSP_ContextListener;

/**
 * This object contains current information about the state of the game.
 *
 */
/*
 * This file is part of the USIP Open Simulation Platform.

 *
 * The USIP Open Simulation Platform is free software; you can redistribute it
 * and/or modify it under the terms of the new BSD Style license associated with
 * this distribution.

 *
 * The USIP Open Simulation Platform is distributed WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE.

 */
public class GamePhaseCurrentTime {

	public GamePhaseCurrentTime(){

	}

	/** Simulation id. */
	private Long simId;

	/** phase id. */
	private Long phaseId;

	/** Running simulation id. */
	private Long rsId;

	/** Id of the GameClockPhaseInstruction under control at this time. */
	private Long gcpiId;

	private String dateFormat = "MM/dd/yy HH:mm:ss a";

	/** formatting on time output. */
	private java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(dateFormat);

	/** If counting toward some deadline, this is it. */
	private Date dateTripPoint = new java.util.Date();

	/** A deadline expressed as a long number. */
	private long longTripPoint = 0;

	/** Identifies the type of timer. */
	private int timerType = 0;

	/**
	 * If time is chunked into things (such as days, months, etc.) how many
	 * milliseconds per chunk.
	 */
	private long timeInterval = 0;

	/**
	 * It time is chunked into things (such as days, months, etc.) the display
	 * name of the chunk.
	 */
	private String intervalName = "";

	/** The number of the interval (1, 2, 3, etc.) that we are on. */
	private long currentInterval = 0;

	/** Time that the current interval began. */
	private Date currentIntervalStartTime = new Date();

	/** Time that the current interval began, expressed as a long. */
	private long currentIntervalStartTimeLong = 0;

	/** Difference between system time and game time, expressed as a long. */
	private long timeOffset = 0;

	/** Indicates if this timer has been initialized. */
	private boolean initialized = false;

	private void initialize() {
		currentIntervalStartTime = new Date();
		currentIntervalStartTimeLong = currentIntervalStartTime.getTime();

		currentInterval = 0;
		initialized = true;
	}

	/**
	 *
	 * @param request
	 * @return
	 */
	private String calculateGameTime(HttpServletRequest request) {

		if (!initialized) {
			initialize();
		}

		String returnString = "Undefined Time with timerType: " + timerType;
		// /
		switch (timerType) {
		case (GameClockPhaseInstructions.GCPI_CONST):
			returnString = ("constant");
			break;
		case (GameClockPhaseInstructions.GCPI_UP_TIME):
			returnString = ("up time");
			break;
		case (GameClockPhaseInstructions.GCPI_UP_RUNNING_TIME):
			returnString = ("up running time");
			break;
		case (GameClockPhaseInstructions.GCPI_UP_INTERVAL):
			long millisSinceLast = new Date().getTime()
					- currentIntervalStartTimeLong;

			if (millisSinceLast >= currentInterval) {
				++currentInterval;
				System.out.println(currentInterval);
				// Reset clock for next interval.
				millisSinceLast = 0;
				currentIntervalStartTime = new Date();
				currentIntervalStartTimeLong = currentIntervalStartTime
						.getTime();

			}
			returnString = this.intervalName + " " + currentInterval;

			break;
		case (GameClockPhaseInstructions.GCPI_DOWN_TIME):
			returnString = ("down time");
			break;
		case (GameClockPhaseInstructions.GCPI_DOWN_RUNNING_TIME):
			returnString = ("down running time");
			break;
		case (GameClockPhaseInstructions.GCPI_DOWN_INTERVAL):
			returnString = ("down interval");
			break;
		}

		return returnString;
	}

	public String getGameTime(HttpServletRequest request, SessionObjectBase sob) {
		return calculateGameTime(request);
	}

	/**
	 * Pulls the GPCT for this phase (if one exists) out of the cache. If one
	 * does not exist, it returns an empty gpct.
	 *
	 * @param request
	 * @param schema
	 * @param simId
	 * @param rsId
	 * @param phaseId
	 * @return
	 */
	public static GamePhaseCurrentTime pullGPCTFromCache(
			HttpServletRequest request, String schema, Long simId, Long rsId,
			Long phaseId) {

		Hashtable databaseHash = USIP_OSP_Cache.getCachedHashtable(request,
				USIP_OSP_ContextListener.getCacheonGametimer(schema));

		GamePhaseCurrentTime gpct = (GamePhaseCurrentTime) databaseHash
				.get(rsId);

		if (gpct == null) {

			gpct = new GamePhaseCurrentTime();

		}

		return gpct;
	}

	public static void putGPCTInCache(HttpServletRequest request,
			String schema, Long simId, Long rsId, Long phaseId,
			GamePhaseCurrentTime gpct) {

		Hashtable databaseHash = USIP_OSP_Cache.getCachedHashtable(request,
				USIP_OSP_ContextListener.getCacheonGametimer(schema));

		databaseHash.put(rsId, gpct);

	}

	public Long getSimId() {
		return simId;
	}

	public void setSimId(Long simId) {
		this.simId = simId;
	}

	public Long getPhaseId() {
		return phaseId;
	}

	public void setPhaseId(Long phaseId) {
		this.phaseId = phaseId;
	}

	public Long getRsId() {
		return rsId;
	}

	public void setRsId(Long rsId) {
		this.rsId = rsId;
	}

	public Long getGcpiId() {
		return gcpiId;
	}

	public void setGcpiId(Long gcpiId) {
		this.gcpiId = gcpiId;
	}

	public String getDateFormat() {
		return dateFormat;
	}

	public void setDateFormat(String dateFormat) {
		this.dateFormat = dateFormat;
	}

	public java.text.SimpleDateFormat getSdf() {
		return sdf;
	}

	public void setSdf(java.text.SimpleDateFormat sdf) {
		this.sdf = sdf;
	}

	public Date getDateTripPoint() {
		return dateTripPoint;
	}

	public void setDateTripPoint(Date dateTripPoint) {
		this.dateTripPoint = dateTripPoint;
	}

	public long getLongTripPoint() {
		return longTripPoint;
	}

	public void setLongTripPoint(long longTripPoint) {
		this.longTripPoint = longTripPoint;
	}

	public long getCurrentInterval() {
		return currentInterval;
	}

	public void setCurrentInterval(long currentInterval) {
		this.currentInterval = currentInterval;
	}

	public Date getCurrentIntervalStartTime() {
		return currentIntervalStartTime;
	}

	public void setCurrentIntervalStartTime(Date currentIntervalStartTime) {
		this.currentIntervalStartTime = currentIntervalStartTime;
	}

	public long getCurrentIntervalStartTimeLong() {
		return currentIntervalStartTimeLong;
	}

	public void setCurrentIntervalStartTimeLong(
			long currentIntervalStartTimeLong) {
		this.currentIntervalStartTimeLong = currentIntervalStartTimeLong;
	}

	public long getTimeOffset() {
		return timeOffset;
	}

	public void setTimeOffset(long timeOffset) {
		this.timeOffset = timeOffset;
	}

	public boolean isInitialized() {
		return initialized;
	}

	public void setInitialized(boolean initialized) {
		this.initialized = initialized;
	}

	public int getTimerType() {
		return timerType;
	}

	public void setTimerType(int timerType) {
		this.timerType = timerType;
	}

	public long getTimeInterval() {
		return timeInterval;
	}

	public void setTimeInterval(long timeInterval) {
		this.timeInterval = timeInterval;
	}

	public String getIntervalName() {
		return intervalName;
	}

	public void setIntervalName(String intervalName) {
		this.intervalName = intervalName;
	}

}


text:
from django.db import models
from django.utils.translation import ugettext as _
from event_kiosk.events.models import Event
from datetime import datetime

class Presentation(models.Model):
    name = models.CharField(_('name'), max_length=255, help_text=_('Reference name for this presentation. Only visible in the admin.'))
    transitionTime = models.PositiveIntegerField(_('transition time'), help_text=_('Number of seconds to display each slide.'))
    pauseTimeOnTouch = models.PositiveIntegerField(_('pause time on touch'), help_text=_('If someone interacts with the kiosk, stop the slideshow for this number of seconds.'))

    headerImage = models.ImageField(_('header image'), upload_to='headers/', null=True, blank=True)

    displayMenu = models.BooleanField(_('display menu'), default=True, help_text=_('Whether or not the menu should appear on this presentation.'))
    displayIndicators = models.BooleanField(_('display indicators'), default=True, help_text=_('Whether or not to display the little dots at the bottom that show slideshow progress.'))

    def __str__(self):
        return self.name

class Slide(models.Model):
    IMAGE = 'image'
    EVENT = 'event'
    EVENT_LIST = 'eventList'
    WEATHER = 'weather'

    SLIDE_TYPE_CHOICES = (
        ('', ''),
        (IMAGE, _('Image')),
        (EVENT, _('Event')),
        (EVENT_LIST, _('Event list')),
        (WEATHER, _('Weather')),
    )

    MONTHLY = 'MONTHLY'
    DAILY = 'DAILY'

    EVENT_LIST_SLIDE_FORMAT_CHOICES = (
        (MONTHLY, _('Monthly')),
        (DAILY, _('Daily'))
    )

    presentation = models.ForeignKey(to=Presentation, related_name="slides", null=False, blank=False)
    type = models.CharField(_('type'), max_length=32, choices=SLIDE_TYPE_CHOICES, default=None, blank=False, null=False)

    # Image slide background image
    image = models.ImageField(_('image'), upload_to='slides/%Y/%m/%d/', null=True, blank=True)

    # Event slide event
    event = models.ForeignKey(to=Event, related_name="slides", null=True, blank=True)

    # Event list slide display type
    displayType = models.CharField(_('event list display type'), max_length=32,
                                          choices=EVENT_LIST_SLIDE_FORMAT_CHOICES, default=MONTHLY,
                                          blank=False, null=False)

    position = models.PositiveIntegerField(default=0, blank=False, null=False)

    # Weather slide information
    location = models.CharField(_('location'), help_text=_('A comma-delimited country name and country code (ISO 3166)'), max_length=255, null=True, blank=True)
    lat = models.DecimalField(_('latitude'), null=True, blank=True, max_digits=10, decimal_places=7)
    lon = models.DecimalField(_('longitude'), null=True, blank=True, max_digits=10, decimal_places=7)

    def to_json(self):
        if (self.type == 'image'):
            return {
                'type': 'image',
                'title': '',
                'img': self.image.url
            }

        elif (self.type == 'event'):
            return {
                'type': 'event',
                'title': self.event.shortTitle if self.event.shortTitle != '' else self.event.title,
                'event': self.event.to_json()
            }

        elif (self.type == 'weather'):
            return {
                'type': 'weather',
                'location': self.location,
                'lat': self.lat,
                'lon': self.lon,
                'title': ''
            }

        elif (self.type == 'eventList'):
            events = Event.objects.filter(
                date__gte=datetime.today()
            ).order_by('date', 'startTime', 'shortTitle', 'title')
            events_json = []
            for event in events:
                events_json.append(event.to_json())

            return {
                'type': 'eventList',
                'title': _('Upcoming events'),
                'displayType': self.displayType,
                'events': events_json
            }

    def __str__(self):
        return 'Slide'

    class Meta(object):
        ordering = ('position', )


text:
require 'rails/generators'

class CrashlogGenerator < Rails::Generators::Base
  argument :api_key, :type => :string
  class_option :force, :aliases => "-f", :type => :boolean, :desc => "Replace existing crashlog.rb file"
  source_root File.expand_path("../../../../../generators/crashlog/templates", __FILE__)

  def install
    ensure_api_key_is_valid_format
    generate_initializer unless api_key_configured?
    test_crashlog
  end

  private

  def ensure_api_key_is_valid_format
    unless api_key_pair_provided?
      puts "API_KEY does not match required format: <KEY>:<SECRET>"
      exit(1)
    end
  end

  def api_key_pair_provided?
    !!(self.api_key =~ /^(\h){8}-(\h){4}-(\h){4}-(\h){4}-(\h){12}\:\w+$/)
  end

  def api_key_pair
    /(?<api_key>^(\h){8}-(\h){4}-(\h){4}-(\h){4}-(\h){12})\:(?<secret>\w+)$/.match(self.api_key)
  end

  def api_key_expression
    api_key = api_key_pair[:api_key]
    "'#{api_key}'"
  end

  def secret_expression
    secret = api_key_pair[:secret]
    "'#{secret}'"
  end

  def generate_initializer
    template 'initializer.rb', 'config/initializers/crashlog.rb'
  end

  def api_key_configured?
    return false if options[:force]
    File.exists?('config/initializers/crashlog.rb')
  end

  def test_crashlog
    run("rake crashlog:test")
  end
end


text: ../STAR-Fusion -J Chimeric.out.junction.gz --verbose_level 2