text:
import signal
import asyncio
import threading
import time
from concurrent.futures import CancelledError
from pipetree.artifact import Artifact
from pipetree.stage import PipelineStageFactory
from pipetree.config import PipelineStageConfig

class ExecutorServer(object):
    """
    A multi purpose executor server, accepting serialized
    tasks as jobs, allowing outside services to
    monitor task completion.

    Tasks should be the output of ExecutorTask.serialize(),
    which contains a JSON list of Artifact.meta_to_dict() as well
    as a stage definition.
    """
    def __init__(self, backend, executor, loop=None):
        self._backend = backend
        self._executor = executor
        self._job_count = 0
        self._jobs = {}
        self._lock = threading.Lock()
        self._loop = loop or asyncio.get_event_loop()
        self._queue = asyncio.Queue(loop=self._loop)

    def _log(self, message):
        print("ExecutorServer: %s" % message)

    def enqueue_job(self, job):
        """
        Accept the JSON representation of a task and its artifacts.
        returns a unique job ID

        Tasks should be the output of ExecutorTask.serialize(),
        which contains a JSON list of Artifact.meta_to_dict() as well
        as stage information
        """

        job_id = -1
        with self._lock:
            self._job_count += 1
            job_id = self._job_count
            self._jobs[job_id] = {"status": "queued"}
        self._queue.put_nowait((job_id, job))
        return job_id

    def retrieve_job(self, job_id):
        """
        Retrieve the current status and/or result for the given job.
        """
        job = {}
        with self._lock:
            if job_id not in self._jobs:
                return None
            job = self._jobs[job_id]
        return job

    async def _run_job(self, job):
        # Get stage from pipeline
        pf = PipelineStageFactory()
        config = PipelineStageConfig(job['stage_name'], job['stage_config'])
        stage = pf.create_pipeline_stage(config)

        # Load input artifact payloads from cache
        loaded_artifacts = []
        for artifact in job['artifacts']:
            art_obj = Artifact(stage._config)
            art_obj.meta_from_dict(artifact)
            loaded = self._backend.load_artifact(art_obj)
            if loaded is None:
                self._log("Could not find payload for artifact")
                raise Exception("Could not find payload for artifact")
            loaded_artifacts.append(loaded)

        # Execute the task
        exec_task = self._executor.create_task(stage, loaded_artifacts)
        result = await exec_task.generate_artifacts()

        for art in result:
            art._creation_time = float(time.time())
            art._dependency_hash = Artifact.dependency_hash(loaded_artifacts)
            self._backend.save_artifact(art)
        self._backend.log_pipeline_stage_run_complete(
            config,
            Artifact.dependency_hash(loaded_artifacts))

        return result

    async def _listen_to_queue(self):
        while True:
            self._log("Listening on queue")
            job_id, job = await self._queue.get()
            self._log('Acquired job for stage: %s' % job['stage_name'])
            result_artifacts = await self._run_job(job)
            with self._lock:
                self._jobs[job_id] = {"status": "complete",
                                      "artifacts": result_artifacts,
                                      "job": job}
                self._log("Job complete: %d for stage %s" %
                          (job_id,  job['stage_name']))

    def shutdown(self):
        for task in asyncio.Task.all_tasks():
            task.cancel()

    async def _close_after(self, num_seconds):
        if num_seconds is None:
            return
        await asyncio.sleep(num_seconds)
        self.shutdown()
        raise CancelledError

    def run_event_loop(self, close_after=None):
        self._loop.add_signal_handler(signal.SIGHUP, self.shutdown)
        self._loop.add_signal_handler(signal.SIGINT, self.shutdown)
        self._loop.add_signal_handler(signal.SIGTERM, self.shutdown)

        try:
            self._loop.run_until_complete(asyncio.wait([
                self._close_after(close_after),
                self._listen_to_queue()
            ]))
        except CancelledError:
            self._log('CancelledError raised: closing event loop.')
        finally:
            self._loop.close()


text:
;(async () => {
  const json = await fetch('https://www.zhihu.com/api/v4/notifications/v2/vote_thank').then(res => res.json())
  return json.data.map(x => ({
    message: `${
      Array.isArray(x.content.actors)
    ? x.content.actors.map(actor => actor.name).join('、')
    : x.content.actors.name
    } ${ x.content.verb } ${ x.content.target.text }`
  , iconUrl: 'avatar_url_template' in x.target.author
    ? x.target.author.avatar_url_template.replace('{size}', 'im')
    : 'https://static.zhihu.com/static/revved/img/ios/touch-icon-120.496c913b.png'
  , url: x.content.target.link
  }))
})().then(commit)

redpajama_set_name: RedPajamaGithub


text:
from os import listdir, mkdir, symlink
from os.path import exists, isdir, islink, join

XCODEROOT = '/Developer/Xcode'
MYSDKROOT = '/Developer/SDKs'
APPSDKROOT = '/Applications/Xcode.app/Contents/Developer/Platforms'  # '/Developer/_test'
PLATFORMS = [d for d in listdir(APPSDKROOT) if d.endswith('.platform')]

def my_mkdir(path):
    if not exists(path):
        mkdir(path)

def ensure_platform_dirs():
    for p in PLATFORMS:
        platform_dir = join(APPSDKROOT, p)
        developer_dir = join(platform_dir, 'Developer')
        sdks_dir = join(developer_dir, 'SDKs')

        my_mkdir(platform_dir)
        my_mkdir(developer_dir)
        my_mkdir(sdks_dir)

def get_available_xcodes():
    # Get all folders matching the form 'Xcode <VERSION>.app'
    versions = [x for x in listdir(XCODEROOT) if isdir(join(XCODEROOT, x)) and x.startswith('Xcode ') and x.endswith('.app')]

    # Append those version numbers to our list and return it
    result = []
    [result.append(v[6:-4]) for v in versions]
    return reversed(sorted(result))

def main():
    ensure_platform_dirs()
    xcodes = get_available_xcodes()

    for version in xcodes:
        xcode_dir = join(XCODEROOT, 'Xcode {0}.app'.format(version))
        xcp_dir = join(xcode_dir, 'Contents/Developer/Platforms')

        for platform in PLATFORMS:
            platform_dir = join(xcp_dir, platform)

            if exists(platform_dir):
                sdks_dir = join(platform_dir, 'Developer/SDKs')
                sdks = [d for d in listdir(sdks_dir) if isdir(sdks_dir) and d.endswith('.sdk') and not islink(join(sdks_dir, d))]

                for sdk in sdks:
                    source = join(sdks_dir, sdk)
                    destination = join(join(APPSDKROOT, platform), 'Developer/SDKs/' + sdk)
                    versioned = sdk[-5:-4].isdigit()

                    if versioned and not exists(destination):
                        symlink(source, destination)
                        print 'Linked ' + sdk + ' from Xcode ' + version + ' (' + platform + ')'

if __name__ == '__main__':
    main()


text:
from django import template
from django.template.loader import get_template
from django.core.files.storage import get_storage_class
from .. import settings

register = template.Library()

@register.simple_tag
def get_favicons(prefix=None):
    """
    Generate HTML to include in headers for get all favicons url.

    :param prefix: Prefix of files' names
    :type prefix: str
    :return: HTML link and meta
    :rtype: str
    """
    return get_template('favicon/favicon.html').render({
        'prefix': prefix
    })

@register.simple_tag
def favicon_url(filename, prefix=None):
    """
    Generate URL for find a single file. It uses :meth:`url()` of storage
    defined in ``settings.FAVICON_STORAGE``.

    :param filename: Filename
    :type filename: str
    :param prefix: Prefix of filename
    :type prefix: str
    :return: File's URL
    :rtype: str
    """
    storage = get_storage_class(settings.STORAGE)(**settings.STORAGE_OPTIONS)
    prefix = prefix or ''
    name = prefix + filename
    return storage.url(name)


text:
package com.amazonaws.services.ecs.model.transform;

import java.util.List;
import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.ecs.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * ContainerInstanceMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class ContainerInstanceMarshaller {

    private static final MarshallingInfo<String> CONTAINERINSTANCEARN_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("containerInstanceArn").build();
    private static final MarshallingInfo<String> EC2INSTANCEID_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("ec2InstanceId").build();
    private static final MarshallingInfo<Long> VERSION_BINDING = MarshallingInfo.builder(MarshallingType.LONG).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("version").build();
    private static final MarshallingInfo<StructuredPojo> VERSIONINFO_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("versionInfo").build();
    private static final MarshallingInfo<List> REMAININGRESOURCES_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("remainingResources").build();
    private static final MarshallingInfo<List> REGISTEREDRESOURCES_BINDING = MarshallingInfo.builder(MarshallingType.LIST)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("registeredResources").build();
    private static final MarshallingInfo<String> STATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("status").build();
    private static final MarshallingInfo<String> STATUSREASON_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("statusReason").build();
    private static final MarshallingInfo<Boolean> AGENTCONNECTED_BINDING = MarshallingInfo.builder(MarshallingType.BOOLEAN)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("agentConnected").build();
    private static final MarshallingInfo<Integer> RUNNINGTASKSCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("runningTasksCount").build();
    private static final MarshallingInfo<Integer> PENDINGTASKSCOUNT_BINDING = MarshallingInfo.builder(MarshallingType.INTEGER)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("pendingTasksCount").build();
    private static final MarshallingInfo<String> AGENTUPDATESTATUS_BINDING = MarshallingInfo.builder(MarshallingType.STRING)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("agentUpdateStatus").build();
    private static final MarshallingInfo<List> ATTRIBUTES_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("attributes").build();
    private static final MarshallingInfo<java.util.Date> REGISTEREDAT_BINDING = MarshallingInfo.builder(MarshallingType.DATE)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("registeredAt").timestampFormat("unixTimestamp").build();
    private static final MarshallingInfo<List> ATTACHMENTS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("attachments").build();
    private static final MarshallingInfo<List> TAGS_BINDING = MarshallingInfo.builder(MarshallingType.LIST).marshallLocation(MarshallLocation.PAYLOAD)
            .marshallLocationName("tags").build();

    private static final ContainerInstanceMarshaller instance = new ContainerInstanceMarshaller();

    public static ContainerInstanceMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(ContainerInstance containerInstance, ProtocolMarshaller protocolMarshaller) {

        if (containerInstance == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(containerInstance.getContainerInstanceArn(), CONTAINERINSTANCEARN_BINDING);
            protocolMarshaller.marshall(containerInstance.getEc2InstanceId(), EC2INSTANCEID_BINDING);
            protocolMarshaller.marshall(containerInstance.getVersion(), VERSION_BINDING);
            protocolMarshaller.marshall(containerInstance.getVersionInfo(), VERSIONINFO_BINDING);
            protocolMarshaller.marshall(containerInstance.getRemainingResources(), REMAININGRESOURCES_BINDING);
            protocolMarshaller.marshall(containerInstance.getRegisteredResources(), REGISTEREDRESOURCES_BINDING);
            protocolMarshaller.marshall(containerInstance.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(containerInstance.getStatusReason(), STATUSREASON_BINDING);
            protocolMarshaller.marshall(containerInstance.getAgentConnected(), AGENTCONNECTED_BINDING);
            protocolMarshaller.marshall(containerInstance.getRunningTasksCount(), RUNNINGTASKSCOUNT_BINDING);
            protocolMarshaller.marshall(containerInstance.getPendingTasksCount(), PENDINGTASKSCOUNT_BINDING);
            protocolMarshaller.marshall(containerInstance.getAgentUpdateStatus(), AGENTUPDATESTATUS_BINDING);
            protocolMarshaller.marshall(containerInstance.getAttributes(), ATTRIBUTES_BINDING);
            protocolMarshaller.marshall(containerInstance.getRegisteredAt(), REGISTEREDAT_BINDING);
            protocolMarshaller.marshall(containerInstance.getAttachments(), ATTACHMENTS_BINDING);
            protocolMarshaller.marshall(containerInstance.getTags(), TAGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
using System;
using Xamarin.Forms;

namespace MyShop
{
	public class HomeViewModel : BaseViewModel
	{
		public HomeViewModel  (Page page) : base (page)
		{
			Title = "My Shoppe";
		}

	}
}


text:
$(document).ready(function() {

  // First THREE values can be changed to control game behavior...
  var seconds = 20; // max time for each question to be answered
  var shortGame = 5; // shortens game play by not using all 25 questions
  var answerTime = 4; // number of seconds #answer-wrapper displays
  var gameLength;
  var gameLengthFull;
  var randNumArr = [];
  var currentQuestion;
  var currentOptions;
  var currentAnswer;
  var currentImage;
  var intervalId;
  var timeoutId;
  var secondsCountdown;
  var outOfTime;
  var questionCount;
  var correctAnswerTotal;
  var incorrectAnswerTotal;
  var unAnswerTotal;

  // Audio variables
  var audioElem = $('.audio');
  var audio = new Audio('assets/audio/StevieWonder_BlackMan.mp3');
  audio.volume = 1;
  audio.loop = true;
  audio.mute = true;

  var triviaGame = {
    questions: {
      q1: {
        question: 'Who was the first man to die for the American flag?',
        options: ['Paul Revere', 'Crispus Attucks', 'Benjamin Franklin', 'Amerigo Vespucci'],
        answer: 'Crispus Attucks',
        answerImg: 'assets/images/crispus_attucks.jpg'
      },
      q2: {
        question: 'Who were the first people on the ground in America?',
        options: ['Vikings', 'Spanish', 'Native Americans', 'English'],
        answer: 'Native Americans',
        answerImg: 'assets/images/native_americans.jpg'
      },
      q3: {
        question: 'Who was the guide on the first Columbus trip?',
        options: ['Cristobal Colon', 'Juan de la Cosa', 'Diego de Arana', 'Pedro Alonso Niño'],
        answer: 'Pedro Alonso Niño',
        answerImg: 'assets/images/pedro_alonso_nino.jpg'
      },
      q4: {
        question: 'Who laid the first railroad tracks connecting the United States?',
        options: ['Italian workers', 'French workers', 'Canadian workers', 'Chinese workers'],
        answer: 'Chinese workers',
        answerImg: 'assets/images/chinese_workers.png'
      },
      q5: {
        question: 'Who was the first heart surgeon?',
        options: ['Dr. Daniel Hale Williams', 'Dr. Strangelove', 'Dr. Peter Leavitt', 'Dr. Benjamin Spock'],
        answer: 'Dr. Daniel Hale Williams',
        answerImg: 'assets/images/daniel_hale_williams.jpg'
      },
      q6: {
        question: 'Who showed the pilgrims at Plymouth the secrets of survival in the New World?',
        options: ['John Horse', 'Squanto', 'Anakin', 'Sitting Bull'],
        answer: 'Squanto',
        answerImg: 'assets/images/squanto.png'
      },
      q7: {
        question: 'Who was a California leader fighting for farm workers\' dignity, respect, and labor rights?',
        options: ['Octaviano Larrazolo', 'Junipero Serra', 'Cesar Chavez', 'José Martí'],
        answer: 'Cesar Chavez',
        answerImg: 'assets/images/cesar_chavez.jpg'
      },
      q8: {
        question: 'Who was the inventor of incandescent light bulb?',
        options: ['Eli Whitney', 'Thomas Edison', 'Ralph Waldo Emerson', 'Charles Goodyear'],
        answer: 'Thomas Edison',
        answerImg: 'assets/images/thomas_edison.jpg'
      },
      q9: {
        question: 'Who helped design the nation\'s capitol, created the first clock in America, and wrote almanacs?',
        options: ['Benjamin Banneker', 'Nicolas Norton', 'Jared James', 'Raymond Reed'],
        answer: 'Benjamin Banneker',
        answerImg: 'assets/images/benjamin_banneker.png'
      },
      q10: {
        question: 'Who was the heroine that helped scout the Lewis and Clark expedition?',
        options: ['Black Hawk', 'Crazy Horse', 'Sacagawea', 'Cochise',],
        answer: 'Sacagawea',
        answerImg: 'assets/images/sacagawea.jpg'
      },
      q11: {
        question: 'Who was a primary pioneer of martial arts in America?',
        options: ['Joe Lewis', 'Jet Li', 'Chuck Norris', 'Bruce Lee'],
        answer: 'Bruce Lee',
        answerImg: 'assets/images/bruce_lee.jpg'
      },
      q12: {
        question: 'Who signed the Emancipation Proclamation, freeing more than 3 million U.S. slaves?',
        options: ['James Garfield', 'Abraham Lincoln', 'William McKinley', 'Andrew Jackson'],
        answer: 'Abraham Lincoln',
        answerImg: 'assets/images/abraham_lincoln.jpg'
      },
      q13: {
        question: 'Who was once widely recognized as first man to set foot on the North Pole?',
        options: ['William Edward Parry', 'Hjalmar Johansen', 'Matthew Henson', 'Richard Byrd'],
        answer: 'Matthew Henson',
        answerImg: 'assets/images/matthew_henson.jpg'
      },
      q14: {
        question: 'Who was a soldier of Company G and won high honors in World War I?',
        options: ['Sing Lee', 'Raoul Wallenberg', 'Oskar Schindler', 'Douglas Bader'],
        answer: 'Sing Lee',
        answerImg: 'assets/images/sing_lee_company_g.jpg'
      },
      q15: {
        question: 'Who created processes for storage of blood plasma and was the director of the Red Cross blood bank?',
        options: ['Dr. Ian Frazer', 'Dr. Carl Jung', 'Dr. René Laennec', 'Dr. Charles Drew'],
        answer: 'Dr. Charles Drew',
        answerImg: 'assets/images/charles_drew.jpg'
      },
      q16: {
        question: 'Who was a famous educator and semanticist who made contributions to education in America?',
        options: ['Daniel Inouye', 'Mako Iwamatsu', 'Saburo Muraoka', 'Hayakawa'],
        answer: 'Hayakawa',
        answerImg: 'assets/images/hayakawa.jpg'
      },
      q17: {
        question: 'Who invented the world\'s first stop light and gas mask?',
        options: ['Fritz Haber', 'Garrett Morgan', 'Robert Oppenheimer', 'Jacques Cousteau'],
        answer: 'Garrett Morgan',
        answerImg: 'assets/images/garrett_morgan.gif'
      },
      q18: {
        question: 'Who was a surgeon that pioneered neurosurgery?',
        options: ['Harvey William Cushing', 'Joseph Lister', 'Thomas Starzl', 'Christiaan Barnard'],
        answer: 'Harvey William Cushing',
        answerImg: 'assets/images/harvey_williams_cushing.jpg'
      },
      q19: {
        question: 'Who was the hero that helped establish the league of Iroquois?',
        options: ['Hiawatha', 'Chief Joseph', 'Black Elk', 'Chief Seattle'],
        answer: 'Hiawatha',
        answerImg: 'assets/images/hiawatha.jpg'
      },
      q20: {
        question: 'Who was the leader of the first macrobiotic center in America?',
        options: ['Vera Richter', 'Frances Moore Lappé', 'Michio Kushi', 'Robert Atkins'],
        answer: 'Michio Kushi',
        answerImg: 'assets/images/michio-kushi.jpg'
      },
      q21: {
        question: 'Who founded of the city of Chicago in 1772?',
        options: ['Viceroy Bucareli', 'Sam Houston', 'Jean Baptiste', 'William Sherman'],
        answer: 'Jean Baptiste',
        answerImg: 'assets/images/jean_baptiste_point_du_sable.jpg'
      },
      q22: {
        question: 'Who was one of the organizers of the American Indian Movement?',
        options: ['Dennis Banks', 'Huey P. Newton', 'Felix Longoria', 'Angela Davis'],
        answer: 'Dennis Banks',
        answerImg: 'assets/images/dennis_banks.jpg'
      },
      q23: {
        question: 'Who was the Jewish financier who raised funds to sponsor Christopher Columbus\' voyage to America?',
        options: ['Leif Eriksson', 'Luis de Santángel', 'Ferdinand Magellan', 'Ibn Battuta'],
        answer: 'Luis de Santángel',
        answerImg: 'assets/images/luis_de_santangel.jpg'
      },
      q24: {
        question: 'Who lead slaves to freedom on the Underground Railroad?',
        options: ['Solomon Northup', 'Thomas Jefferson', 'Harriet Tubman', 'Sojourner Truth'],
        answer: 'Harriet Tubman',
        answerImg: 'assets/images/harriet_ross_tubman.png'
      },
      q25: {
        question: 'Who is known as the inventor of the fire extinguisher but actually invented the firefighting standpipe?',
        options: ['T.J. Marshall', 'Tom Westman', 'Dan White', 'Jan Van der Heyden'],
        answer: 'T.J. Marshall',
        answerImg: 'assets/images/tjmarshall_standpipe.jpg'
      }
    },
    startGame: function(){
      randNumGenerator();
      outOfTime = false;
      questionCount = 0;
      correctAnswerTotal = 0;
      incorrectAnswerTotal = 0;
      unAnswerTotal = 0;
      $('.time-remaining').text(seconds);
      $('#game-start').hide();
      $('#game-over').hide();
      $('.sidebar').show();
      $('#game').show();
      triviaGame.setQuestion();
    },
    setQuestion: function(){
        console.log(questionCount);
      outOfTime = false;
      $('#options-wrapper').empty();
      currentQuestion = triviaGame.questions['q' + randNumArr[questionCount]].question;
      currentOptions = triviaGame.questions['q' + randNumArr[questionCount]].options;
      currentAnswer = triviaGame.questions['q' + randNumArr[questionCount]].answer;
      currentImage = triviaGame.questions['q' + randNumArr[questionCount]].answerImg;
      $('#question').text(currentQuestion);
      for (i = 0; i < currentOptions.length; i++) {
        var currentOption = triviaGame.questions['q' + randNumArr[questionCount]].options[i];
        var buttonId = '#button' + (i + 1);
        var newButton = $('<button>').attr({
          id: buttonId,
          class: 'option-button',
          'data-option': currentOption
        }).text(currentOption);
        $('#options-wrapper').append(newButton);
      }
      questionCount++;
      run();
    },
    checkAnswer: function(chosenAnswer){
      if (chosenAnswer === currentAnswer) {
        triviaGame.correctAnswer();
      } else {
        triviaGame.incorrectAnswer();
      }
    },
    correctAnswer: function(){
      correctAnswerTotal++;
      $('#options-wrapper, #answer-text, #answer-image').empty();
      var newResponse = $('
').html('Correct!  The answer is ' + currentAnswer + '.');
      $('#answer-text').append(newResponse);
      var newImage = $('').attr('src', currentImage);
      $('#answer-image').append(newImage);
      $('#answer-wrapper').show();
      timeoutId = setTimeout(triviaGame.nextStep, 1000 * answerTime);
    },
    incorrectAnswer: function(){
      $('#options-wrapper, #answer-text, #answer-image').empty();
      if (outOfTime) {
        var timeUpResponse = $('
').html('Out of Time!');
        $('#answer-text').prepend(timeUpResponse);
        unAnswerTotal++;
      } else {
        incorrectAnswerTotal++;
      }
      var newResponse = $('
').html('Sorry.  The answer is ' + currentAnswer + '.');
      $('#answer-text').append(newResponse);
      var newImage = $('').attr('src', currentImage);
      $('#answer-image').append(newImage);
      $('#answer-wrapper').show();
      timeoutId = setTimeout(triviaGame.nextStep, 1000 * answerTime);
    },
    nextStep: function(){
      clearTimeout(timeoutId);
        // console.log('nextStep --> gameLength: ' + gameLength + ' / questionCount: ' + questionCount + ' / randNumArr[questionCount]: ' + randNumArr[questionCount] + ' / correctAnswerTotal: ' + correctAnswerTotal + ' incorrectAnswerTotal: ' + incorrectAnswerTotal + ' unAnswerTotal: ' + unAnswerTotal);
      $('#answer-wrapper').hide();
      if (questionCount === gameLength) {
        triviaGame.endGame();
      } else {
        triviaGame.setQuestion();
      }
      $('.time-remaining').text(seconds);
    },
    endGame: function(){
      $('.sidebar').hide();
      $('#game').hide();
      $('#correct-answers').text(correctAnswerTotal);
      $('#incorrect-answers').text(incorrectAnswerTotal);
      $('#unanswer-answers').text(unAnswerTotal);
      $('#game-over').show();
    },
  };

  // Generate Random Non-Repeating Number within Object Length Range
  function randNumGenerator() {
    // define number array
    for (var i = 1; i <= gameLengthFull; i++) {
      randNumArr[i] = i;
    }
      randNumArr.shift();
    // randomize array
    randNumArr.sort(function () {
      return Math.random() - 0.5;
    });
  }

  // Timer functions
  function run() {
    secondsCountdown = seconds;
    intervalId = setInterval(decrement, 1000);
  }
  function decrement() {
    secondsCountdown--;
    $('.time-remaining').text(secondsCountdown);
    if (secondsCountdown === 0) {
      stop();
      outOfTime = true;
      triviaGame.incorrectAnswer(outOfTime);
    }
  }
  function stop() {
    clearInterval(intervalId);
  }

  // Sets time remaining figure in intro text on page
  $('.time-remaining').text(seconds);

  // Click behaviors
  $('.start').on('click', function() {
    gameLengthFull = Object.keys(triviaGame.questions).length;
    if ($(this).hasClass('short-game')) {
      gameLength = shortGame;
    } else {
      gameLength = gameLengthFull;
    }
    triviaGame.startGame();
  });
  $(document).on('click', '.option-button', function() {
    var clickOption = $(this).attr('data-option');
    stop();
    triviaGame.checkAnswer(clickOption);
  });

  // Controls background audio after and during new games
  function audioControl() {
    if (audio.mute === true) {
      audio.play();
      $('#audio-toggle').show();
      $('.audio').html('Pause Song ♬');
      audio.mute = false;
    } else  {
      audio.pause();
      $('.audio').html('Play Song ♬');
      audio.mute = true;
    }
  }
  $('.audio').on('click', function(){
    audioControl();
  });

});


text:
package org.ldp4j.application.kernel.template;

import org.ldp4j.application.ext.ContainerHandler;
import org.ldp4j.application.kernel.template.DirectContainerTemplate;
import org.ldp4j.application.kernel.template.TemplateVisitor;

final class MutableDirectContainerTemplate extends MutableMembershipAwareContainerTemplate implements DirectContainerTemplate {

	MutableDirectContainerTemplate(String id, Class<? extends ContainerHandler> handlerClass) {
		super(id, handlerClass);
	}

	@Override
	public void accept(TemplateVisitor visitor) {
		visitor.visitDirectContainerTemplate(this);
	}

}


text:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title>jsTree v.1.0 - sort documentation</title>

	<link type="text/css" rel="stylesheet" href="syntax/!style.css"/>
	<link type="text/css" rel="stylesheet" href="!style.css"/>

jsTree v.1.0

sort plugin

Description

The sort enables jstree to automatically sort all nodes using a specified function. This means that when the user creates, renames or moves nodes around - they will automatically sort.

Configuration

Expects a function. The functions receives two arguments - two nodes to be compared. Return -1 or 1 (or any other different from -1). Default is:

function (a, b) { return this.get_text(a) > this.get_text(b) ? 1 : -1; }

Demos

Using the sort plugin

<input type="button" class="button" value="rename" id="rename" style="" />

			Root node 1

					Child node 1

					Child node 2

			Root node 2

API

.sort ( node )

Sorts the children of the specified node - this function is called automatically.

		mixed node

This can be a DOM node, jQuery node or selector pointing to the element.


text:
package instrumentationTest.de.test.antennapod.service.download;

import android.test.InstrumentationTestCase;
import android.util.Log;
import de.danoeh.antennapod.feed.FeedFile;
import de.danoeh.antennapod.service.download.DownloadRequest;
import de.danoeh.antennapod.service.download.DownloadStatus;
import de.danoeh.antennapod.service.download.Downloader;
import de.danoeh.antennapod.service.download.HttpDownloader;
import de.danoeh.antennapod.util.DownloadError;
import instrumentationTest.de.test.antennapod.util.service.download.HTTPBin;

import java.io.File;
import java.io.IOException;

public class HttpDownloaderTest extends InstrumentationTestCase {
    private static final String TAG = "HttpDownloaderTest";
    private static final String DOWNLOAD_DIR = "testdownloads";

    private static boolean successful = true;

    private File destDir;

    private HTTPBin httpServer;

    public HttpDownloaderTest() {
        super();
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        File[] contents = destDir.listFiles();
        for (File f : contents) {
            assertTrue(f.delete());
        }

        httpServer.stop();
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        destDir = getInstrumentation().getTargetContext().getExternalFilesDir(DOWNLOAD_DIR);
        assertNotNull(destDir);
        assertTrue(destDir.exists());
        httpServer = new HTTPBin();
        httpServer.start();
    }

    private FeedFileImpl setupFeedFile(String downloadUrl, String title, boolean deleteExisting) {
        FeedFileImpl feedfile = new FeedFileImpl(downloadUrl);
        String fileUrl = new File(destDir, title).getAbsolutePath();
        File file = new File(fileUrl);
        if (deleteExisting) {
            Log.d(TAG, "Deleting file: " + file.delete());
        }
        feedfile.setFile_url(fileUrl);
        return feedfile;
    }

    private Downloader download(String url, String title, boolean expectedResult) {
        return download(url, title, expectedResult, true, null, null, true);
    }

    private Downloader download(String url, String title, boolean expectedResult, boolean deleteExisting, String username, String password, boolean deleteOnFail) {
        FeedFile feedFile = setupFeedFile(url, title, deleteExisting);
        DownloadRequest request = new DownloadRequest(feedFile.getFile_url(), url, title, 0, feedFile.getTypeAsInt(), username, password, deleteOnFail);
        Downloader downloader = new HttpDownloader(request);
        downloader.call();
        DownloadStatus status = downloader.getResult();
        assertNotNull(status);
        assertTrue(status.isSuccessful() == expectedResult);
        assertTrue(status.isDone());
        // the file should not exist if the download has failed and deleteExisting was true
        assertTrue(!deleteExisting || new File(feedFile.getFile_url()).exists() == expectedResult);
        return downloader;
    }

    private static final String URL_404 = HTTPBin.BASE_URL + "/status/404";
    private static final String URL_AUTH = HTTPBin.BASE_URL + "/basic-auth/user/passwd";

    public void testPassingHttp() {
        download(HTTPBin.BASE_URL + "/status/200", "test200", true);
    }

    public void testRedirect() {
        download(HTTPBin.BASE_URL + "/redirect/4", "testRedirect", true);
    }

    public void testGzip() {
        download("http://httpbin.org/gzip", "testGzip", true);
    }

    public void test404() {
        download(URL_404, "test404", false);
    }

    public void testCancel() {
        final String url = HTTPBin.BASE_URL + "/delay/3";
        FeedFileImpl feedFile = setupFeedFile(url, "delay", true);
        final Downloader downloader = new HttpDownloader(new DownloadRequest(feedFile.getFile_url(), url, "delay", 0, feedFile.getTypeAsInt()));
        Thread t = new Thread() {
            @Override
            public void run() {
                downloader.call();
            }
        };
        t.start();
        downloader.cancel();
        try {
            t.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        DownloadStatus result = downloader.getResult();
        assertTrue(result.isDone());
        assertFalse(result.isSuccessful());
        assertTrue(result.isCancelled());
        assertFalse(new File(feedFile.getFile_url()).exists());
    }

    public void testDeleteOnFailShouldDelete() {
        Downloader downloader = download(URL_404, "testDeleteOnFailShouldDelete", false, true, null, null, true);
        assertFalse(new File(downloader.getDownloadRequest().getDestination()).exists());
    }

    public void testDeleteOnFailShouldNotDelete() throws IOException {
        String filename = "testDeleteOnFailShouldDelete";
        File dest = new File(destDir, filename);
        dest.delete();
        assertTrue(dest.createNewFile());
        Downloader downloader = download(URL_404, filename, false, false, null, null, false);
        assertTrue(new File(downloader.getDownloadRequest().getDestination()).exists());
    }

    public void testAuthenticationShouldSucceed() throws InterruptedException {
        download(URL_AUTH, "testAuthSuccess", true, true, "user", "passwd", true);
    }

    public void testAuthenticationShouldFail() {
        Downloader downloader = download(URL_AUTH, "testAuthSuccess", false, true, "user", "Wrong passwd", true);
        assertEquals(DownloadError.ERROR_UNAUTHORIZED, downloader.getResult().getReason());
    }

    /* TODO: replace with smaller test file
    public void testUrlWithSpaces() {
        download("http://acedl.noxsolutions.com/ace/Don't Call Salman Rushdie Sneezy in Finland.mp3", "testUrlWithSpaces", true);
    }
    */

    private static class FeedFileImpl extends FeedFile {
        public FeedFileImpl(String download_url) {
            super(null, download_url, false);
        }

        @Override
        public String getHumanReadableIdentifier() {
            return download_url;
        }

        @Override
        public int getTypeAsInt() {
            return 0;
        }
    }

}


text:
/*	$OpenBSD: cmdtab.c,v 1.7 2006/03/17 14:43:06 moritz Exp $	*/
/*	$NetBSD: cmdtab.c,v 1.3 1994/12/08 09:30:46 jtc Exp $	*/

/*
 * Copyright (c) 1983, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
__FBSDID("$FreeBSD: soc2013/dpl/head/usr.bin/tip/tip/cmdtab.c 161824 2006-08-31 19:19:44Z ru $");

#ifndef lint
#if 0
static char sccsid[] = "@(#)cmdtab.c	8.1 (Berkeley) 6/6/93";
static const char rcsid[] = "$OpenBSD: cmdtab.c,v 1.7 2006/03/17 14:43:06 moritz Exp $";
#endif
#endif /* not lint */

#include "tip.h"

esctable_t etable[] = {
	{ '!',	NORM,	"shell",			 shell },
	{ '<',	NORM,	"receive file from remote host", getfl },
	{ '>',	NORM,	"send file to remote host",	 sendfile },
	{ 't',	NORM,	"take file from remote UNIX",	 cu_take },
	{ 'p',	NORM,	"put file to remote UNIX",	 cu_put },
	{ '|',	NORM,	"pipe remote file",		 pipefile },
	{ '$',	NORM,	"pipe local command to remote host", pipeout },
#ifdef CONNECT
	{ 'C',  NORM,	"connect program to remote host",consh },
#endif
	{ 'c',	NORM,	"change directory",		 chdirectory },
	{ '.',	NORM,	"exit from tip",		 finish },
	{CTRL('d'),NORM,"exit from tip",		 finish },
	{CTRL('y'),NORM,"suspend tip (local+remote)",	 suspend },
	{CTRL('z'),NORM,"suspend tip (local only)",	 suspend },
	{ 's',	NORM,	"set variable",			 variable },
	{ 'v',	NORM,	"list variables",		 listvariables },
	{ '?',	NORM,	"get this summary",		 help },
	{ '#',	NORM,	"send break",			 genbrk },
	{ '\0',	0,	NULL,				 NULL }
};