text:
import TracksData from "./TracksData"
import { apiCall } from "helpers"

class TracksAlbumData extends TracksData {
  ALBUM_LIMIT = 20

  tracks: any[]

  constructor(accessToken: string, tracks: any[]) {
    super(accessToken)
    this.tracks = tracks
  }

  dataLabels() {
    return ["Album Genres", "Label", "Copyrights"]
  }

  async data() {
    const albumIds = Array.from(new Set(this.tracks.filter((track: any) => track.album.id).map((track: any) => track.album.id)))

    let requests = []

    for (var offset = 0; offset < albumIds.length; offset = offset + this.ALBUM_LIMIT) {
      requests.push(`https://api.spotify.com/v1/albums?ids=${albumIds.slice(offset, offset + this.ALBUM_LIMIT)}`)
    }

    const albumPromises = requests.map((request) => apiCall(request, this.accessToken))
    const albumResponses = await Promise.all(albumPromises)

    const albumDataById = new Map<string, string[]>(
      albumResponses.flatMap((response) => response.data.albums.map((album: any) => {
        return [
          album == null ? "" : album.id,
          [
            album == null ? "" : album.genres.join(", "),
            album == null ? "" : album.label,
            album == null ? "" : album.copyrights.map((c: any) => `${c.type} ${c.text}`).join(", ")
          ]
        ]
      }))
    )

    return new Map<string, string[]>(
      this.tracks.map((track: any) => [track.uri, albumDataById.get(track.album.id) || ["", "", ""]])
    )
  }
}

export default TracksAlbumData


text:
import os
import json
import random
import collections
from interfaces import NTRTJobMaster, NTRTMasterError
from concurrent_scheduler import ConcurrentScheduler
import collections
#TODO: This is hackety, fix it.
from evolution_job import EvolutionJob

class LastUpdatedOrderedDict(collections.OrderedDict):
    'Store items in the order the keys were last added'

    def __setitem__(self, key, value):
        if key in self:
            del self[key]
        collections.OrderedDict.__setitem__(self, key, value)

class EvolutionJobMaster(NTRTJobMaster):
    def _setup(self):
        """
        Read input file, store file paths for run
        """

        # If this fails, the program should fail. Input file is required
        # for useful output
        try:
            fin = open(self.configFileName, 'r')
            self.jConf = json.load(fin)
            fin.close()
        except IOError:
            raise NTRTMasterError("Please provide a valid configuration file")

        self.path = self.jConf['resourcePath'] + self.jConf['lowerPath']

        try:
            os.makedirs(self.path)
        except OSError:
            if not os.path.isdir(self.path):
                raise NTRTMasterError("Directed the folder path to an invalid address")

        try:
            os.makedirs(self.path + '/logs')
        except OSError:
            if not os.path.isdir(self.path + '/logs'):
                raise NTRTMasterError("Please create logs directory at" + self.path)

        # Consider seeding random, using default (system time) now
        #random.seed(5)

    def __writeToNNW(self, neuralParams, fileName):
        """
        Take the params (neuralParams) and write them to a .nnw file for reading by
        the neuralNetwork code (Third party library)
        """
        fout = open(fileName, 'w')
        first = True
        for x in neuralParams:
            if (first):
                fout.write(str(x))
                first = False
            else:
                fout.write("," + str(x))

    def __getNewParams(self, paramName):
        """
        Generate a new set of paramters based on learning method and config file
        Returns a dictionary paramName : values
        This is the implementation of monteCarlo
        """
        params = self.jConf["learningParams"][paramName]

        pMax = params['paramMax']
        pMin = params['paramMin']

        newController = {}
        newController['paramID'] = str(self.paramID)

        # Neural network or not. Slightly different data structure
        if params['numberOfStates'] == 0 :

            newParams = []

            for i in range(0, params['numberOfInstances']) :
                subParams = []
                for j in range(0, params['numberOfOutputs']) :
                    # Assume scaling happens elsewhere
                    subParams.append(random.uniform(pMin, pMax))
                newParams.append(subParams)
        else :
            newParams = { 'numActions' : params['numberOfOutputs'],
                         'numStates' : params['numberOfStates'],
                         'numHidden' : params['numberHidden'],
                         'neuralFilename' : "logs/bestParameters-test_fb-"+ newController['paramID'] +".nnw"}

            neuralParams = []

            numStates = params['numberOfStates']
            numOutputs=  params['numberOfOutputs']
            numHidden = params['numberHidden']

            totalParams = (numStates + 1) * (numHidden) + (numHidden + 1) * numOutputs

            for i in range(0,  totalParams) :
                neuralParams.append(random.uniform(pMin, pMax))

            newParams['neuralParams'] = neuralParams

            self.__writeToNNW(neuralParams, self.path + newParams['neuralFilename'])

        newController['params'] = newParams
        newController['scores'] = []

        return newController

    def __mutateParams(self, currentController, paramName):
        """
        Change some parameters (according to mutationChance) by an amount sampled from a gaussian
        (mutationDev)
        """
        params = self.jConf["learningParams"][paramName]

        pMax = params['paramMax']
        pMin = params['paramMin']

        # Slightly different encoding for neural nets
        if(params['numberOfStates'] > 0):
            cNew = list(currentController['neuralParams'])
        else:
            # Make a deep copy
            cNew = list(currentController)

        for i, v in enumerate(cNew):
            if isinstance(v, collections.Iterable):
                v = self.__mutateParams(v, paramName)
            else:
                if(random.random() > params['mutationChance']):

                    mutAmount = random.normalvariate(0.0, params['mutationDev'])
                    v += mutAmount

                    if (v > pMax):
                        v = pMax
                    elif (v < pMin):
                        v = pMin
            cNew[i] = v

        # Slightly different encoding for neural nets
        if(params['numberOfStates'] > 0):
            newNeuro = {}
            newNeuro['neuralParams'] = cNew
            newNeuro['numStates'] = params['numberOfStates']
            newNeuro['numActions'] =  params['numberOfOutputs']
            newNeuro['numHidden'] =  params['numberHidden']
            return newNeuro
        else:
            return cNew

    def __getControllerFromProbability(self, currentGeneration, prob):
        """
        A support function for genetic algorithms that selects a controller
        based on the distribution of probabilities for all of their controllers (their
        contriution to the total score of the generation)
        """
        for c in currentGeneration.itervalues():
            if (c['probability'] < prob):
                break

        return c

        raise NTRTMasterError("Insufficient values to satisfy requested probability")

    def __getChildController(self, c1, c2, params):
        """
        Takes two controllers and merges them with a 50/50 chance of selecting
        a parameter from each controller
        """

        if(params['numberOfStates'] > 0):
            c1 = list(c1['neuralParams'])
            c2 = list(c2['neuralParams'])

        cNew = []

        if (len(c1) == 0):
            raise NTRTMasterError("Error in length")

        """
        # Old code for random params
        for i, j in zip(c1, c2):
            # Go to the deepest level of the parameters (see instances in the specification)
            if isinstance(i, collections.Iterable):
                cNew.append(self.__getChildController(i, j, params))
            else:
                # @todo should this be adjustable?
                if (random.random() > 0.5):
                    cNew.append(i)
                else:
                    cNew.append(j)
        """
        crossOver = random.randint(0, len(c1) - 1)

        print(crossOver)

        cNew[0:crossOver] = c1[0:crossOver]
        print(len(cNew))

        cNew[crossOver:len(c2)+1] = c2[crossOver:len(c2)+1]
        print(len(cNew))

        if (len(cNew) != len(c1)):
            raise NTRTMasterError("Error in length")

        if(params['numberOfStates'] > 0):
            newNeuro = {}
            newNeuro['neuralParams'] = cNew
            newNeuro['numStates'] = params['numberOfStates']
            newNeuro['numActions'] =  params['numberOfOutputs']
            newNeuro['numHidden'] =  params['numberHidden']
            return newNeuro
        else:
            return cNew

    def __sortAvg(self, x):
        """
        Returns the average score from a controller for sorting
        """

        return x['avgScore']

    def __sortMax(self, x):
        """
        Returns the max score of a controller for sorting
        """

        return x['maxScore']

    def generationGenerator(self, currentGeneration, paramName):
        """
        Master function that takes an existing set of paramters, sorts them by score
        and then returns a new set of parameters based on the specification file
        """

	numTrials = self.jConf['learningParams']['numTrials']

        params = self.jConf["learningParams"][paramName]

        useAvg = params['useAverage']

        nextGeneration = LastUpdatedOrderedDict()

        # Are we doing monteCarlo or starting a new trial?
        if (len(currentGeneration) == 0 or params['monteCarlo']):

            # Starting a new trial - load previous results, if any, unless doing monteCarlo
            if (not (params['learning'] and params['monteCarlo'])):
                for i in range(0, params['startingControllers']):
                    inFile = self.path + self.jConf['filePrefix'] + "_" + str(i) + self.jConf['fileSuffix']
                    # We want the IO error if this fails
                    fin = open(inFile, 'r')
                    jControl = json.load(fin)
                    fin.close()
                    controller = {}
                    # Check how controller was generated
                    try:
                        controller['params'] = jControl[paramName]['params']
                    except KeyError:
                        controller['params'] = jControl[paramName]
                    except TypeError:
                        controller['params'] = jControl[paramName]
                    controller['paramID'] = str(self.paramID)
                    controller['scores'] = []
                    nextGeneration.__setitem__(controller['paramID'], controller)

                    self.paramID += 1

            # Fill in remaining population with random parameters
            for i in range(len(nextGeneration), params['populationSize']):
		if(params['monteCarlo'] and params['populationSize'] != numTrials):
	            raise NTRTMasterError("Number of trials must equal population size!")
                if (i < 0):
                    raise NTRTMasterError("Number of controllers greater than population size!")

                controller = self.__getNewParams(paramName)
                nextGeneration.__setitem__(controller['paramID'], controller)
                self.paramID += 1

        elif (not params['learning']):
            # Not learning, return previous controllers
            nextGeneration = currentGeneration

        else:
            # learning, not doing monteCarlo, have a previous generation

            popSize = len(currentGeneration)

            # order the prior population

            for k, controller in currentGeneration.iteritems() :
                scores = controller['scores']
                controller['maxScore'] = max(scores)
                controller['avgScore'] = sum(scores) / float(len(scores))

            if (useAvg):
                key = lambda x: x[1]['avgScore']
            else:
                key = lambda x: x[1]['maxScore']
            sortedGeneration = collections.OrderedDict(sorted(currentGeneration.items(), None, key, True))

            scoreDump = open('scoreDump.txt', 'a')
            scoreDump.write(json.dumps(sortedGeneration))
            scoreDump.write('\n')
            scoreDump.close()

            totalScore = 0

            # Get probabilities for children (for mating)

            if (useAvg):

                for controller in sortedGeneration.itervalues():
                    pass

                floor = controller['avgScore']

                for controller in sortedGeneration.itervalues():
                    totalScore += controller['avgScore'] - floor

                first = True
                c1 = {}

                # All scores are the same for some reason, don't divide by zero
                if totalScore == 0.0:
                    totalScore = 1

                for c in sortedGeneration.itervalues():
                    if first:
                        c['probability'] = (c['avgScore'] - floor) / totalScore
                        first = False
                    else:
                        c['probability'] = (c['avgScore'] - floor) / totalScore + c1['probability']
                    c1 = c

            else:
                for controller in sortedGeneration.itervalues():
                    pass

                floor = controller['maxScore']

                for controller in sortedGeneration.itervalues():
                    totalScore += controller['maxScore'] - floor

                first = True
                c1 = {}
                # All scores are the same for some reason, don't divide by zero
                if totalScore == 0.0:
                    totalScore = 1
                for c in sortedGeneration.itervalues():
                    if first:
                        c['probability'] = (c['maxScore'] - floor) / totalScore
                        first = False
                    else:
                        c['probability'] = (c['maxScore'] - floor) / totalScore + c1['probability']
                    c1 = c

            # How many of the best controllers are we keeping?
            numElites = popSize - (params['numberToMutate'] + params['numberOfChildren'])

            if (numElites < 0):
                raise NTRTMasterError("Population slated to grow in size! Please adjust population size, number to mutate and/or number of children")

            # Copy elites to new generation
            count = 0
            for c in sortedGeneration.itervalues():
                # Stop when number of elites has been reached
                if (count >= numElites):
                    break

                nextGeneration.__setitem__(c['paramID'], c)
                if c['params'] == None:
                    raise NTRTMasterError("Found it!")
                count += 1

            # Add 'asexual' mutations to next generation.
            # TODO: make option that assigns mutations to random controllers, rather than just mutating top N
            count = 0
            for c in sortedGeneration.itervalues():
                if (count >= params['numberToMutate']):
                    break
                cNew = {}
                cNew['params'] = self.__mutateParams(c['params'], paramName)
                cNew['paramID'] = str(self.paramID)
                cNew['scores'] = []

                nextGeneration.__setitem__(cNew['paramID'], cNew)
                self.paramID += 1

                if cNew['params'] == None:
                    raise NTRTMasterError("Found it!")

                count += 1

            # Add children to new generation
            for i in range(params['numberOfChildren']):

                c1Prob = random.random()
                c2Prob = random.random()

                c1 = self.__getControllerFromProbability(sortedGeneration, c1Prob)
                c2 = self.__getControllerFromProbability(sortedGeneration, c2Prob)

                while (c1 == c2):
                    c2Prob = random.random()
                    c2 = self.__getControllerFromProbability(sortedGeneration, c2Prob)

                cNew = {}
                cNew['params'] = self.__getChildController(c1['params'], c2['params'], params)

                if (random.random() >= params['childMutationChance']):
                    cNew['params'] = self.__mutateParams(cNew['params'], paramName)

                cNew['paramID'] = str(self.paramID)
                cNew['scores'] = []

                nextGeneration.__setitem__(cNew['paramID'], cNew)
                self.paramID += 1

                if cNew['params'] == None:
                    raise NTRTMasterError("Found it!")

            if (len(nextGeneration) != popSize):
                raise NTRTMasterError("Failed to generate the correct number of controllers")

            if (params['numberOfStates'] > 0):
                for c in nextGeneration.itervalues():
                    c['params']['neuralFilename'] = "logs/bestParameters-test_fb-"+ c['paramID'] +".nnw"
                    self.__writeToNNW(c['params']['neuralParams'], self.path + c['params']['neuralFilename'])

        return nextGeneration

    def getParamID(self, gen, jobNum):
        """
        Get the controller's key based on the job number
        """
        try:
            return list(gen)[jobNum]
        except IndexError:
            print 'Not enough keys'

    def getNewFile(self, jobNum):
        """
        Handle the generation of a new JSON file with new parameters. Will vary based on the
        learning method used and the config file
        Edit this based on your parameter set
        """

        obj = {}

        for p in self.prefixes:
            # Hacked co-evolution. Normally co-evolution would always select a random controller
            if(jobNum >= len(self.currentGeneration[p])):
                paramNum = random.randint(0, len(self.currentGeneration[p]) - 1)
            else:
                paramNum = jobNum

            obj[p + "Vals"] = self.currentGeneration[p][self.getParamID(self.currentGeneration[p], paramNum)]

	obj["metrics"] = [] # Added to store tension and COM data.

	outFile = self.path + self.jConf['filePrefix'] + "_" + str(jobNum) + self.jConf['fileSuffix']

        fout = open(outFile, 'w')

        json.dump(obj, fout, indent=4)

        return self.jConf['filePrefix'] + "_" + str(jobNum) + self.jConf['fileSuffix']

    def getJobNum(self, paramNum, paramName):

        for i in range(0, len(self.currentGeneration[paramName])):
            if paramNum == self.currentGeneration[paramName][i]['paramID']:
                break

        return i

    def beginTrial(self):
        """
        Override this. It should just contain a loop where you keep constructing NTRTJobs, then calling
        runJob on it (which will block you until the NTRT instance returns), parsing the result from the job, then
        deciding if you should run another trial or if you want to terminate.
        """

        # Start a counter job ids to be use in dictionaries
        self.paramID = 1

        numTrials = self.jConf['learningParams']['numTrials']
        numGenerations = self.jConf['learningParams']['numGenerations']

        results = {}
        jobList = []

        lParams = self.jConf['learningParams']

        self.prefixes = []

        for keys in lParams:
            if keys[-4:] == "Vals":
                self.prefixes.append(keys[:-4])

        print (self.prefixes)

        self.currentGeneration = {}
        for p in self.prefixes:
            self.currentGeneration[p] = {}

        logFile = open('evoLog.txt', 'w') #Clear logfile
        logFile.close()

        scoreDump = open('scoreDump.txt', 'w')
        scoreDump.close()
        for n in range(numGenerations):
            # Create the generation'
            for p in self.prefixes:
                self.currentGeneration[p] = self.generationGenerator(self.currentGeneration[p], p + 'Vals')

            # Iterate over the generation (change range..)
            if n > 0:
                startTrial = self.jConf['learningParams']['deterministic']
            else:
                startTrial = 0

            # We want to write all of the trials for post processing
            for i in range(0, numTrials) :

                # MonteCarlo solution. This function could be overridden with something that
                # provides a filename for a pre-existing file
                fileName = self.getNewFile(i)

                for j in self.jConf['terrain']:
                    # All args to be passed to subprocess must be strings

                    args = {'filename' : fileName,
                            'resourcePrefix' : self.jConf['resourcePath'],
                            'path'     : self.jConf['lowerPath'],
                            'executable' : self.jConf['executable'],
                            'length'   : self.jConf['learningParams']['trialLength'],
                            'terrain'  : j}
                    if (n == 0 or i >= startTrial):
                        jobList.append(EvolutionJob(args))

            # Run the jobs
            conSched = ConcurrentScheduler(jobList, self.numProcesses)
            completedJobs = conSched.processJobs()

            # Read scores from files, write to logs
            totalScore = 0
            maxScore = -1000
            for job in completedJobs:
                job.processJobOutput()
                jobVals = job.obj

                scores = jobVals['scores']

                # Iterate through all of the new scores for this file
                for i in scores:
                    score = i['distance']

                    for p in self.prefixes:
                        if (lParams[p + 'Vals']['learning']):
                            key = jobVals [p + 'Vals']['paramID']
                            self.currentGeneration[p][key]['scores'].append(score)

                    totalScore += score
                    if score > maxScore:
                        maxScore = score

            avgScore = totalScore / float(len(completedJobs) * len(self.jConf['terrain']) )
            logFile = open('evoLog.txt', 'a')
            logFile.write(str((n+1) * numTrials) + ',' + str(maxScore) + ',' + str(avgScore) +'\n')
            logFile.close()

redpajama_set_name: RedPajamaGithub


text:
package net.shangtech.studio.dao.impl;

import net.shangtech.framework.dao.hibernate.BaseDao;
import net.shangtech.studio.dao.ISpecialPageDao;
import net.shangtech.studio.entity.SpecialPage;
import org.springframework.stereotype.Repository;

@Repository
public class SpecialPageDao extends BaseDao<SpecialPage> implements ISpecialPageDao {

}


text:
module HTTP
  # MIME type encode/decode adapters
  module MimeType
    class << self
      # Associate MIME type with adapter
      #
      # @example
      #
      #   module JsonAdapter
      #     class << self
      #       def encode(obj)
      #         # encode logic here
      #       end
      #
      #       def decode(str)
      #         # decode logic here
      #       end
      #     end
      #   end
      #
      #   HTTP::MimeType.register_adapter 'application/json', MyJsonAdapter
      #
      # @param [#to_s] type
      # @param [#encode, #decode] adapter
      # @return [void]
      def register_adapter(type, adapter)
        adapters[type.to_s] = adapter
      end

      # Returns adapter associated with MIME type
      #
      # @param [#to_s] type
      # @raise [Error] if no adapter found
      # @return [Class]
      def [](type)
        adapters[normalize type] || fail(Error, "Unknown MIME type: #{type}")
      end

      # Register a shortcut for MIME type
      #
      # @example
      #
      #   HTTP::MimeType.register_alias 'application/json', :json
      #
      # @param [#to_s] type
      # @param [#to_sym] shortcut
      # @return [void]
      def register_alias(type, shortcut)
        aliases[shortcut.to_sym] = type.to_s
      end

      # Resolves type by shortcut if possible
      #
      # @param [#to_s] type
      # @return [String]
      def normalize(type)
        aliases.fetch type, type.to_s
      end

    private

      # :nodoc:
      def adapters
        @adapters ||= {}
      end

      # :nodoc:
      def aliases
        @aliases ||= {}
      end
    end
  end
end

# built-in mime types
require 'http/mime_type/json'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _09._2DRectangleArea
{
    class Program
    {
        static void Main(string[] args)
        {
            double x1 = double.Parse(Console.ReadLine());
            double y1 = double.Parse(Console.ReadLine());
            double x2 = double.Parse(Console.ReadLine());
            double y2 = double.Parse(Console.ReadLine());

            double X = x1 - x2;
            if (X<0)
            {
                X *= -1;
            }
            double Y = y1 - y2;
            if (Y<0)
            {
                Y *= -1;

            }
            double area = X * Y;
            double perimeter = 2 * (X + Y);

            Console.WriteLine(area);
            Console.WriteLine(perimeter);
        }
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ParsedMessage.cs" company="">
//
// </copyright>
// <summary>
//   The parsed message.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace PenguinSdk
{
    using EEPhysics;

    /// <summary>
    /// The parsed message.
    /// </summary>
    public class ParsedMessage
    {
        #region Public Properties

        /// <summary>
        /// Gets or sets the caller.
        /// </summary>
        public PhysicsPlayer Caller { get; set; }

        /// <summary>
        /// Gets or sets the raw message.
        /// </summary>
        public string RawMessage { get; set; }

        /// <summary>
        /// Gets or sets the tasks.
        /// </summary>
        public Task[] Tasks { get; set; }

        /// <summary>
        /// Gets or sets the tokens.
        /// </summary>
        public Token[] Tokens { get; set; }

        /// <summary>
        /// Gets or sets the value.
        /// </summary>
        public string Value { get; set; }

        #endregion
    }
}


text:
using System;
using System.Runtime.InteropServices;

namespace Noesis
{

public class BaseAnimation : AnimationTimeline {
  internal new static BaseAnimation CreateProxy(IntPtr cPtr, bool cMemoryOwn) {
    return new BaseAnimation(cPtr, cMemoryOwn);
  }

  internal BaseAnimation(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) {
  }

  internal static HandleRef getCPtr(BaseAnimation obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  protected BaseAnimation() {
  }

  public static DependencyProperty EasingFunctionProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.BaseAnimation_EasingFunctionProperty_get();
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public EasingFunctionBase EasingFunction {
    set {
      NoesisGUI_PINVOKE.BaseAnimation_EasingFunction_set(swigCPtr, EasingFunctionBase.getCPtr(value));
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
    }
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.BaseAnimation_EasingFunction_get(swigCPtr);
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      return (EasingFunctionBase)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  new internal static IntPtr GetStaticType() {
    IntPtr ret = NoesisGUI_PINVOKE.BaseAnimation_GetStaticType();
    if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
    return ret;
  }

}

}


text:
import Ember from 'ember';
import BaseAuthorizer from 'ember-simple-auth/authorizers/base';
const { isEmpty } = Ember;

export default BaseAuthorizer.extend({

  authorize: function(sessionData, block) {
    const tokenAttributeName = 'jwt';
    const userToken = sessionData[tokenAttributeName];
    if (!isEmpty(userToken)) {
      block('Authorization', `Bearer ${userToken}`);
    }}
});


text:
/*
* Initialize Foundation
*/
$(document).foundation();


text:
<?php namespace Pasadinhas\LaravelOAuth\Decorators;

use OAuth\Common\Service\ServiceInterface;

interface ProviderDecoratorContract extends ServiceInterface {

    /**
     * Sets the decorator provider.
     *
     * @param ServiceInterface $provider
     *
     * @return mixed
     */
    public function setProvider(ServiceInterface $provider);

}


text:
/* See LICENSE for licensing information */

#ifndef TOR_CRYPTO_ED25519_H
#define TOR_CRYPTO_ED25519_H

#include "testsupport.h"
#include "torint.h"
#include "crypto_curve25519.h"

#define ED25519_PUBKEY_LEN 32
#define ED25519_SECKEY_LEN 64
#define ED25519_SECKEY_SEED_LEN 32
#define ED25519_SIG_LEN 64

/** An Ed25519 signature. */
typedef struct {
  uint8_t sig[ED25519_SIG_LEN];
} ed25519_signature_t;

/** An Ed25519 public key */
typedef struct {
  uint8_t pubkey[ED25519_PUBKEY_LEN];
} ed25519_public_key_t;

/** An Ed25519 secret key */
typedef struct {
  /** Note that we store secret keys in an expanded format that doesn't match
   * the format from standard ed25519.  Ed25519 stores a 32-byte value k and
   * expands it into a 64-byte H(k), using the first 32 bytes for a multiplier
   * of the base point, and second 32 bytes as an input to a hash function
   * for deriving r.  But because we implement key blinding, we need to store
   * keys in the 64-byte expanded form. */
  uint8_t seckey[ED25519_SECKEY_LEN];
} ed25519_secret_key_t;

/** An Ed25519 keypair. */
typedef struct {
  ed25519_public_key_t pubkey;
  ed25519_secret_key_t seckey;
} ed25519_keypair_t;

int ed25519_secret_key_generate(ed25519_secret_key_t *seckey_out,
                            int extra_strong);
int ed25519_secret_key_from_seed(ed25519_secret_key_t *seckey_out,
                                 const uint8_t *seed);

int ed25519_public_key_generate(ed25519_public_key_t *pubkey_out,
                            const ed25519_secret_key_t *seckey);
int ed25519_keypair_generate(ed25519_keypair_t *keypair_out, int extra_strong);
int ed25519_sign(ed25519_signature_t *signature_out,
                 const uint8_t *msg, size_t len,
                 const ed25519_keypair_t *key);
int ed25519_checksig(const ed25519_signature_t *signature,
                     const uint8_t *msg, size_t len,
                     const ed25519_public_key_t *pubkey);

/**
 * A collection of information necessary to check an Ed25519 signature. Used
 * for batch verification.
 */
typedef struct {
  /** The public key that supposedly generated the signature. */
  const ed25519_public_key_t *pubkey;
  /** The signature to check. */
  ed25519_signature_t signature;
  /** The message that the signature is supposed to have been applied to. */
  const uint8_t *msg;
  /** The length of the message. */
  size_t len;
} ed25519_checkable_t;

int ed25519_checksig_batch(int *okay_out,
                           const ed25519_checkable_t *checkable,
                           int n_checkable);

int ed25519_keypair_from_curve25519_keypair(ed25519_keypair_t *out,
                                            int *signbit_out,
                                            const curve25519_keypair_t *inp);

int ed25519_public_key_from_curve25519_public_key(ed25519_public_key_t *pubkey,
                                     const curve25519_public_key_t *pubkey_in,
                                     int signbit);
int ed25519_keypair_blind(ed25519_keypair_t *out,
                          const ed25519_keypair_t *inp,
                          const uint8_t *param);
int ed25519_public_blind(ed25519_public_key_t *out,
                         const ed25519_public_key_t *inp,
                         const uint8_t *param);

/* XXXX read encrypted, write encrypted. */

int ed25519_seckey_write_to_file(const ed25519_secret_key_t *seckey,
                                 const char *filename,
                                 const char *tag);
int ed25519_seckey_read_from_file(ed25519_secret_key_t *seckey_out,
                                  char **tag_out,
                                  const char *filename);
int ed25519_pubkey_write_to_file(const ed25519_public_key_t *pubkey,
                                 const char *filename,
                                 const char *tag);
int ed25519_pubkey_read_from_file(ed25519_public_key_t *pubkey_out,
                                  char **tag_out,
                                  const char *filename);

void ed25519_keypair_free(ed25519_keypair_t *kp);

int ed25519_pubkey_eq(const ed25519_public_key_t *key1,
                      const ed25519_public_key_t *key2);

void ed25519_set_impl_params(int use_donna);
void ed25519_init(void);

#ifdef TOR_UNIT_TESTS
void crypto_ed25519_testing_force_impl(const char *name);
void crypto_ed25519_testing_restore_impl(void);
#endif

#endif


text:
package tsocket.zby.com.tsocket.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.LinearLayout;
import butterknife.BindView;
import butterknife.ButterKnife;
import java.util.Date;
import tsocket.zby.com.tsocket.AppString;
import tsocket.zby.com.tsocket.R;
import tsocket.zby.com.tsocket.view.wheel.OnWheelChangedListener;
import tsocket.zby.com.tsocket.view.wheel.WheelService;
import tsocket.zby.com.tsocket.view.wheel.WheelView;

/**
 *
Description: 选择执行的定时时间

 * intent传递参数 名, hour, minute,second 不传递值则显示当前时间
 *
 * @author zhujiang
 * @date 2014-7-31
 */
public class WheelTimeActivity extends Activity {

  private final static String TAG = WheelTimeActivity.class.getSimpleName();
  @BindView(R.id.hour_layout) LinearLayout mHourLayout;
  @BindView(R.id.minute_layout) LinearLayout mMinuteLayout;
  @BindView(R.id.second_layout) LinearLayout mSecondLayout;

  //wheel 时间
  private WheelView hour_wheelView;
  private WheelView minute_wheelView;
  private WheelView second_wheelView;
  private final int wheelTextSize = 8;
  private int maxHour = 23, minHour = 0, maxMinute = 59, minMinute = 0, maxSecond = 59, minSecond = 0;

  //handler
  private final int InitWheelView = 3;
  private float phone_density;

  @Override protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_wheel_time);
    ButterKnife.bind(this);

    phone_density = getResources().getDisplayMetrics().density; //屏幕密度
    Window window = getWindow();
    window.setGravity(Gravity.BOTTOM);
    //背景阴影
    LayoutParams lp2 = getWindow().getAttributes();
    lp2.dimAmount = 0.5f;
    getWindow().setAttributes(lp2);
    getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    getWindow().addFlags(LayoutParams.FLAG_DIM_BEHIND);

    initWheelViewThread();
  }

  Handler h = new Handler() {
    public void handleMessage(Message msg) {
      switch (msg.what) {
        case InitWheelView:
          addWheelView();
          initListener();
          initValue();
          break;
        default:
          break;
      }
    }

    ;
  };

  //等待oncreate完成, 给layout高度
  private void initWheelViewThread() {
    new Thread() {
      @Override public void run() {
        int height = 0;
        while (height == 0) {
          if (mHourLayout != null) {
            height = mHourLayout.getHeight();
          }
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
          }
        }

        h.sendEmptyMessage(InitWheelView);
        super.run();
      }
    }.start();
  }

  private void addWheelView() {
    hour_wheelView = new WheelView(this);
    minute_wheelView = new WheelView(this);
    second_wheelView = new WheelView(this);

    Date d = new Date();//没有设定初始值,就用当前时间
    int hour = getIntent().getIntExtra(AppString.HOUR, d.getHours());
    int minute = getIntent().getIntExtra(AppString.MINUTE, d.getMinutes());
    int second = getIntent().getIntExtra(AppString.SECOND, d.getSeconds());

    hour_wheelView = WheelService.getBinInt(this, maxHour, minHour, hour, "  H",
        mHourLayout.getHeight() / wheelTextSize, phone_density);
    mHourLayout.addView(hour_wheelView);
    //		hour_wheelView.setTextColor(getResources().getColor(R.color.text_red), getResources().getColor(R.color.line_between));
    //hour_wheelView.setCenterDrawableSourceId(R.drawable.img_layout_wheel);
    hour_wheelView.setBackgroundColor(getResources().getColor(R.color.text_while));

    minute_wheelView = WheelService.getBinInt(this, maxMinute, minMinute, minute, "  M",
        mMinuteLayout.getHeight() / wheelTextSize, phone_density);
    mMinuteLayout.addView(minute_wheelView);

    second_wheelView = WheelService.getBinInt(this, maxSecond, minSecond, second, " S",
        mSecondLayout.getHeight() / wheelTextSize, phone_density);
    mSecondLayout.addView(second_wheelView);

    if (!getIntent().getBooleanExtra(AppString.SHOW_HOUR, true)) {
      mHourLayout.setVisibility(View.GONE);
    }
  }

  private void initListener() {
    hour_wheelView.addChangingListener(new OnWheelChangedListener() {

      @Override public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        //nowHour = newValue + minHour;
        //listenerDay(nowHour);
      }
    });
    minute_wheelView.addChangingListener(new OnWheelChangedListener() {

      @Override public void onChanged(WheelView wheel, int oldValue, int newValue) {
        //nowMinute = newValue + minMinute;
        //listenerDay(nowMonth);
      }
    });

    second_wheelView.addChangingListener(new OnWheelChangedListener() {

      @Override public void onChanged(WheelView wheel, int oldValue, int newValue) {
        //nowSecond = newValue + minSecond;
        //listenerDay(nowMonth);
      }
    });
  }

  private void initValue() {
    Intent mIntent = getIntent();
    int hourInt = mIntent.getIntExtra(AppString.HOUR, 0);
    int minInt = mIntent.getIntExtra(AppString.MINUTE, 1);
    int secInt = mIntent.getIntExtra(AppString.SECOND, 0);
    if (hourInt == 0 && minInt == 1) {
      Date date = new Date();
      hourInt = date.getHours();
      minInt = date.getMinutes();
      secInt = date.getSeconds();
    }
    hour_wheelView.setCurrentItem(hourInt);
    minute_wheelView.setCurrentItem(minInt);
    second_wheelView.setCurrentItem(secInt);
  }

  public void btn_confirm(View view) {
    Intent intent = getIntent();
    intent.putExtra("hour", hour_wheelView.getCurrentItem() + minHour);
    intent.putExtra("minute", minute_wheelView.getCurrentItem() + minMinute);
    intent.putExtra("second", second_wheelView.getCurrentItem() + minSecond);
    setResult(Activity.RESULT_OK, intent);
    finish();
  }

  public void btn_back(View view) {
    finish();
  }
}


text:
package org.juniversal.translator.cplusplus;

import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.AbstractTypeDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.juniversal.translator.core.ASTUtil;
import org.juniversal.translator.core.SourceFile;
import org.juniversal.translator.core.Translator;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;

public class CPlusPlusTranslator extends Translator {
    private CPPProfile cppProfile = new CPPProfile();

    public CPPProfile getTargetProfile() {
        return cppProfile;
    }

    @Override
    public void translateFile(SourceFile sourceFile) {
        writeCPPFile(sourceFile, OutputType.HEADER);
        writeCPPFile(sourceFile, OutputType.SOURCE);
    }

    private void writeCPPFile(SourceFile sourceFile, OutputType outputType) {
        CompilationUnit compilationUnit = sourceFile.getCompilationUnit();
        TypeDeclaration mainTypeDeclaration = ASTUtil.getFirstTypeDeclaration(compilationUnit);

        String typeName = mainTypeDeclaration.getName().getIdentifier();
        String fileName = outputType == OutputType.HEADER ? typeName + ".h" : typeName + ".cpp";

        File file = new File(getOutputDirectory(), fileName);

        try (FileWriter writer = new FileWriter(file)) {
            CPlusPlusSourceFileWriter cPlusPlusSourceFileWriter = new CPlusPlusSourceFileWriter(this, sourceFile, writer,
                    outputType);

            cPlusPlusSourceFileWriter.writeRootNode(compilationUnit);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String translateNode(SourceFile sourceFile, ASTNode astNode) {
        try (StringWriter writer = new StringWriter()) {
            CPlusPlusSourceFileWriter cPlusPlusSourceFileWriter = new CPlusPlusSourceFileWriter(this, sourceFile, writer,
                    OutputType.SOURCE);

            // Set the type declaration part of the context
            AbstractTypeDeclaration typeDeclaration = (AbstractTypeDeclaration) sourceFile.getCompilationUnit().types().get(0);
            cPlusPlusSourceFileWriter.getContext().setTypeDeclaration(typeDeclaration);

            cPlusPlusSourceFileWriter.writeRootNode(astNode);

            return writer.getBuffer().toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
#ifndef __DAE_TINYXMLPLUGIN__
#define __DAE_TINYXMLPLUGIN__

#include <vector>
#include <list>
#include <dae/daeElement.h>
#include <dae/daeURI.h>
#include <dae/daeIOPluginCommon.h>

class TiXmlDocument;
class TiXmlElement;

class daeTinyXMLPlugin : public daeIOPluginCommon
{
public:
	// Constructor / destructor
	/**
	 * Constructor.
	 */
	DLLSPEC daeTinyXMLPlugin();
	/**
	 * Destructor.
	 */
	virtual DLLSPEC ~daeTinyXMLPlugin();

	// Operations
	virtual DLLSPEC daeInt write(const daeURI& name, daeDocument *document, daeBool replace);

	/**
	 * setOption allows you to set options for this IOPlugin. Which options a plugin supports is
	 * dependent on the plugin itself. There is currently no list of options that plugins are
	 * suggested to implement. daeLibXML2Plugin supports only one option, "saveRawBinary". Set to
	 * "true" to save float_array data as a .raw binary file. The daeRawResolver will convert the
	 * data back into COLLADA domFloat_array elements upon load.
	 * @param option The option to set.
	 * @param value The value to set the option.
	 * @return Returns DAE_OK upon success.
	 */
	virtual DLLSPEC daeInt setOption( daeString option, daeString value );

	/**
	 * getOption retrieves the value of an option from this IOPlugin. Which options a plugin supports is
	 * dependent on the plugin itself.
	 * @param option The option to get.
	 * @return Returns the string value of the option or NULL if option is not valid.
	 */
	virtual DLLSPEC daeString getOption( daeString option );

private:
	TiXmlDocument*  m_doc;
	std::list<TiXmlElement*>  m_elements;

	virtual daeElementRef readFromFile(const daeURI& uri);
	virtual daeElementRef readFromMemory(daeString buffer, const daeURI& baseUri);
	daeElementRef readElement(TiXmlElement* tinyXmlElement, daeElement* parentElement);

	void writeElement( daeElement* element );
	void writeAttribute( daeMetaAttribute* attr, daeElement* element );
	void writeValue( daeElement* element );
};

#endif //__DAE_TINYXMLPLUGIN__


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 140: 150 (1976)

#### Original name
Cercospora pentatropidis S.A. Khan

### Remarks
null


text:
package org.apache.polygene.runtime.query.model;

import org.apache.polygene.api.common.Optional;
import org.apache.polygene.api.property.Property;

public interface Domain
    extends Nameable
{
    @Optional
    Property<String> description();
}


text:
Add Static Image

	 Upload
		<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files, 0)" >


text:
package org.commonjava.indy.ftest.core;

import com.datastax.driver.core.Session;
import com.fasterxml.jackson.databind.Module;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.commonjava.indy.action.IndyLifecycleException;
import org.commonjava.indy.subsys.cassandra.CassandraClient;
import org.commonjava.maven.galley.spi.cache.CacheProvider;
import org.commonjava.propulsor.boot.BootStatus;
import org.commonjava.propulsor.boot.BootException;
import org.commonjava.indy.client.core.Indy;
import org.commonjava.indy.client.core.IndyClientException;
import org.commonjava.indy.client.core.IndyClientModule;
import org.commonjava.indy.model.core.io.IndyObjectMapper;
import org.commonjava.indy.test.fixture.core.CoreServerFixture;
import org.commonjava.util.jhttpc.auth.MemoryPasswordManager;
import org.commonjava.util.jhttpc.model.SiteConfig;
import org.commonjava.util.jhttpc.model.SiteConfigBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestName;
import org.junit.rules.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.enterprise.inject.spi.CDI;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import static org.apache.commons.io.IOUtils.closeQuietly;
import static org.junit.Assert.fail;

public abstract class AbstractIndyFunctionalTest
{
    private static final int NAME_LEN = 8;

    private static final String NAME_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";

    public static final long DEFAULT_TEST_TIMEOUT = 120;

    public static final String TIMEOUT_ENV_FACTOR_SYSPROP = "testEnvTimeoutMultiplier";

    protected Indy client;

    protected CoreServerFixture fixture;

    protected final Logger logger = LoggerFactory.getLogger( getClass() );

    @Rule
    public TestName name = new TestName();

    @Rule
    public Timeout timeout = Timeout.builder()
                                    .withLookingForStuckThread( true )
                                    .withTimeout( getTestTimeoutSeconds(), TimeUnit.SECONDS )
                                    .build();

    protected File etcDir;

    protected File dataDir;

    protected File storageDir;

    protected CacheProvider cacheProvider;

    @SuppressWarnings( "resource" )
    @Before
    public void start()
            throws Throwable
    {
        try
        {
            final long start = System.currentTimeMillis();
            TimerTask task = new TimerTask()
            {
                @Override
                public void run()
                {
                    long time = System.currentTimeMillis();
                    System.out.printf( "\n\n\nDate: %s\nElapsed: %s\n\n\n", new Date( time ),
                                       Duration.between( Instant.ofEpochMilli( start ),
                                                         Instant.ofEpochMilli( time ) ) );
                }
            };

            new Timer().scheduleAtFixedRate( task, 0, 5000 );

            Thread.currentThread().setName( getClass().getSimpleName() + "." + name.getMethodName() );

            fixture = newServerFixture();
            fixture.start();

            if ( !fixture.isStarted() )
            {
                final BootStatus status = fixture.getBootStatus();
                throw new IllegalStateException( "server fixture failed to boot.", status.getError() );
            }

            client = createIndyClient();
            cacheProvider = CDI.current().select( CacheProvider.class ).get();
        }
        catch ( Throwable t )
        {
            logger.error( "Error initializing test", t );
            throw t;
        }
    }

    // Override this if your test do not access storage
    protected boolean isPathMappedStorageEnabled()
    {
        return !isClusterTestSkipped();
    }

    private boolean isClusterTestSkipped()
    {
        return Boolean.parseBoolean( System.getProperty( "skipClusterFTests", "false" ) );
    }

    protected Indy createIndyClient()
            throws IndyClientException
    {
        SiteConfig config = new SiteConfigBuilder( "indy", fixture.getUrl() ).withRequestTimeoutSeconds( 60 ).build();
        Collection<IndyClientModule> modules = getAdditionalClientModules();

        return new Indy( config, new MemoryPasswordManager(), new IndyObjectMapper( getAdditionalMapperModules() ),
                         modules.toArray(new IndyClientModule[modules.size()]) );
    }

    protected float getTestEnvironmentTimeoutMultiplier()
    {
        return Float.parseFloat( System.getProperty( TIMEOUT_ENV_FACTOR_SYSPROP, "1" ) );
    }

    protected void waitForEventPropagation()
    {
        waitForEventPropagationWithMultiplier( getTestTimeoutMultiplier() );
    }

    protected void waitForEventPropagationWithMultiplier( int multiplier )
    {
        long ms = 1000 * multiplier;

        Logger logger = LoggerFactory.getLogger( getClass() );
        logger.info( "Waiting {}ms for Indy server events to clear.", ms );
        // give events time to propagate
        try
        {
            Thread.sleep( ms );
        }
        catch ( InterruptedException e )
        {
            logger.error( e.getMessage(), e );
            fail( "Thread interrupted while waiting for server events to propagate." );
        }

        logger.info( "Resuming test" );
    }

    protected final long getTestTimeoutSeconds()
    {
        return (long) ( getTestTimeoutMultiplier() * getTestEnvironmentTimeoutMultiplier() * DEFAULT_TEST_TIMEOUT );
    }

    protected int getTestTimeoutMultiplier()
    {
        return 1;
    }

    @After
    public void stop()
            throws IndyLifecycleException
    {
        CassandraClient cassandraClient = CDI.current().select( CassandraClient.class ).get();
        dropKeyspace( "cache_" , cassandraClient);
        dropKeyspace( "storage_", cassandraClient );
        dropKeyspace( "schedule_", cassandraClient );
        dropKeyspace( "store_", cassandraClient );

        cassandraClient.close();
        closeCacheProvider();
        closeQuietly( fixture );
        closeQuietly( client );
    }

    // TODO: this is a hack due to the "shutdown action not executed" issue. Once propulsor lifecycle shutdown is applied, this can be replaced.
    private void closeCacheProvider()
    {
        if ( cacheProvider != null )
        {
            cacheProvider.asAdminView().close();
        }
    }

    private void dropKeyspace( String prefix, CassandraClient cassandraClient )
    {
        String keyspace = getKeyspace( prefix );
        logger.debug( "Drop cassandra keyspace: {}", keyspace );
        Session session = cassandraClient.getSession( keyspace );
        if ( session != null )
        {
            try
            {
                session.execute( "DROP KEYSPACE IF EXISTS " + keyspace );
            }
            catch ( Exception ex )
            {
                logger.warn( "Failed to drop keyspace: {}, reason: {}", keyspace, ex );
            }
        }
    }

    protected void sleepAndRunFileGC( long milliseconds )
    {
        try
        {
            Thread.sleep( milliseconds );
        }
        catch ( InterruptedException e )
        {
            logger.error( e.getMessage(), e );
        }
        CacheProvider cacheProvider = CDI.current().select( CacheProvider.class).get();
        cacheProvider.asAdminView().gc();
    }

    protected final CoreServerFixture newServerFixture()
            throws BootException, IOException
    {
        final CoreServerFixture fixture = new CoreServerFixture();

        logger.info( "Setting up configuration using indy.home == '{}'", fixture.getBootOptions().getHomeDir() );
        etcDir = new File( fixture.getBootOptions().getHomeDir(), "etc/indy" );
        dataDir = new File( fixture.getBootOptions().getHomeDir(), "var/lib/indy/data" );
        storageDir = new File( fixture.getBootOptions().getHomeDir(), "var/lib/indy/storage" );

        initBaseTestConfig( fixture );
        initTestConfig( fixture );
        initTestData( fixture );

        return fixture;
    }

    protected <T> T lookup( Class<T> component )    {
        return CDI.current().select( component ).get();
    }

    protected void initTestConfig( CoreServerFixture fixture )
            throws IOException
    {
    }

    protected void initTestData( CoreServerFixture fixture )
            throws IOException
    {
    }

    protected void initBaseTestConfig( CoreServerFixture fixture )
            throws IOException
    {
        writeConfigFile( "conf.d/storage.conf", "[storage-default]\n"
                        + "storage.dir=" + fixture.getBootOptions().getHomeDir() + "/var/lib/indy/storage\n"
                        + "storage.gc.graceperiodinhours=0\n"
                        + "storage.gc.batchsize=0\n"
                        + "storage.cassandra.keyspace=" + getKeyspace( "storage_" ) );

        if ( isClusterTestSkipped() )
        {
            writeConfigFile( "conf.d/default.conf", "[default]"
                            + "\nstandalone=true"
                            + "\naffected.groups.exclude=^build-\\d+"
                            + "\nrepository.filter.enabled=true" );
            writeConfigFile( "conf.d/cassandra.conf", "[cassandra]\nenabled=false" );
        }
        else
        {
            writeConfigFile( "conf.d/default.conf", "[default]\ncache.keyspace=" + getKeyspace( "cache_" )
                            + "\naffected.groups.exclude=^build-\\d+"
                            + "\nrepository.filter.enabled=true\nga-cache.store.pattern=^build-\\d+" );
            writeConfigFile( "conf.d/cassandra.conf", "[cassandra]\nenabled=true" );
        }

        writeConfigFile( "conf.d/store-manager.conf", "[store-manager]\n"
                    + "store.manager.keyspace=" + getKeyspace("store_") + "_stores\nstore.manager.replica=1");

        writeConfigFile( "conf.d/scheduledb.conf", "[scheduledb]\nschedule.keyspace=" + getKeyspace("schedule_" )
                        + "_scheduler\nschedule.keyspace.replica=1\n"
                        + "schedule.partition.range=3600000\nschedule.rate.period=3" );

        writeConfigFile( "conf.d/durable-state.conf", "[durable-state]\n"
                        + "folo.storage=infinispan\n"
                        + "store.storage=infinispan\n"
                        + "schedule.storage=infinispan");

        writeConfigFile( "conf.d/folo.conf", "[folo]\nfolo.cassandra=true"+ "\nfolo.cassandra.keyspace=folo" + "\ntrack.group.content=True");

        if ( isSchedulerEnabled() )
        {
            writeConfigFile( "conf.d/scheduledb.conf", readTestResource( "default-test-scheduledb.conf" ) );
            writeConfigFile( "conf.d/threadpools.conf", "[threadpools]\nenabled=false" );
            writeConfigFile( "conf.d/internal-features.conf", "[_internal]\nstore.validation.enabled=false\nstore.auto.disable.reenable=true\n" );
            writeConfigFile( "conf.d/durable-state.conf", readTestResource( "default-durable-state.conf" ) );
        }
        else
        {
            // TODO: For full clustering test, we would need a remove Infinispan server/cluster...
            writeConfigFile( "conf.d/durable-state.conf", "[durable-state]\n"
                            + "folo.storage=infinispan\n"
                            + "store.storage=infinispan\n"
                            + "schedule.storage=infinispan");

            writeConfigFile( "conf.d/scheduler.conf", "[scheduler]\nenabled=false" );
        }
    }

    private String getKeyspace( String prefix )
    {
        String keyspace = prefix + getClass().getSimpleName();
        if ( keyspace.length() > 48 )
        {
            keyspace = keyspace.substring( 0, 48 ); // keyspace has to be less than 48 characters
        }
        return keyspace;
    }

    protected boolean isSchedulerEnabled()
    {
        return true;
    }

    protected String readTestResource( String resource )
            throws IOException
    {
        return IOUtils.toString( readTestResourceAsStream( resource ) );
    }

    protected InputStream readTestResourceAsStream( String resource )
                    throws IOException
    {
        return Thread.currentThread().getContextClassLoader().getResourceAsStream( resource );
    }

    protected void writeConfigFile( String confPath, String contents )
            throws IOException
    {
        File confFile = new File( etcDir, confPath );
        logger.info( "Writing configuration to: {}\n\n{}\n\n", confFile, contents );

        confFile.getParentFile().mkdirs();

        FileUtils.write( confFile, contents );
    }

    protected void writeDataFile( String path, String contents )
            throws IOException
    {
        File file = new File( dataDir, path );

        logger.info( "Writing data file to: {}\n\n{}\n\n", file, contents );
        file.getParentFile().mkdirs();

        FileUtils.write( file, contents );
    }

    protected void copyToDataFile( String resourcePath, String path ) throws IOException
    {
        File file = new File( dataDir, path );
        logger.info( "Writing data file to: {}, from: {}", file, resourcePath );
        file.getParentFile().mkdirs();
        FileUtils.copyInputStreamToFile(
                        Thread.currentThread().getContextClassLoader().getResourceAsStream( resourcePath ), file );
    }

    protected void copyToConfigFile( String resourcePath, String path ) throws IOException
    {
        File file = new File( etcDir, path );
        logger.info( "Writing data file to: {}, from: {}", file, resourcePath );
        file.getParentFile().mkdirs();
        FileUtils.copyInputStreamToFile(
                        Thread.currentThread().getContextClassLoader().getResourceAsStream( resourcePath ), file );
    }

    protected Collection<Module> getAdditionalMapperModules()
    {
        return Collections.emptySet();
    }

    protected Collection<IndyClientModule> getAdditionalClientModules()
    {
        return Collections.emptySet();
    }

    protected String newName()
    {
        final SecureRandom rand = new SecureRandom();
        final StringBuilder sb = new StringBuilder();
        for ( int i = 0; i < NAME_LEN; i++ )
        {
            sb.append( NAME_CHARS.charAt( ( Math.abs( rand.nextInt() ) % ( NAME_CHARS.length() - 1 ) ) ) );
        }

        return sb.toString();
    }

    protected String newUrl()
    {
        return String.format( "http://%s.com/", newName() );
    }

    protected TemporaryFolder getTemp()
    {
        return fixture.getTempFolder();
    }

    protected boolean isEmpty( String val )
    {
        return val == null || val.length() < 1;
    }

}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import { createBrowserHistory } from 'history';
import { syncHistoryWithStore } from 'react-router-redux';

import createStore from './redux/createStore';
import APIClient from './helpers/APIClient';
import routes from './routes';
import App from './containers/App';

const browserHistory = createBrowserHistory();
const client = new APIClient();
const store = createStore(browserHistory, client);
const history = syncHistoryWithStore(browserHistory, store);

const component = (
	<Provider store={store} key="provider">
		<Router>
			<App>
				{ routes(store) }
			</App>
		</Router>
	</Provider>
);

ReactDOM.render(
	component,
	document.getElementById("app")
);

if (__DEV__ && module.hot) {
	module.hot.accept();
}


text:
package engine

import (
	"bytes"
	"fmt"
	"path"
	"strings"

	"github.com/GoogleContainerTools/kpt/porch/pkg/repository"
	"sigs.k8s.io/kustomize/kyaml/kio"
	"sigs.k8s.io/kustomize/kyaml/kio/kioutil"
	"sigs.k8s.io/kustomize/kyaml/yaml"
)

type packageReader struct {
	input repository.PackageResources
	extra map[string]string
}

var _ kio.Reader = &packageReader{}

func (r *packageReader) Read() ([]*yaml.RNode, error) {
	results := []*yaml.RNode{}
	for k, v := range r.input.Contents {
		base := path.Base(k)
		ext := path.Ext(base)

		// TODO: use authoritative kpt filtering
		if ext != ".yaml" && ext != ".yml" && base != "Kptfile" {
			r.extra[k] = v
			continue
		}

		var reader kio.Reader = &kio.ByteReader{
			Reader: strings.NewReader(v),
			SetAnnotations: map[string]string{
				kioutil.PathAnnotation: k,
			},
			DisableUnwrapping: true,
		}
		nodes, err := reader.Read()
		if err != nil {
			// TODO: fail, or bypass this file too?
			return nil, err
		}
		results = append(results, nodes...)
	}

	return results, nil
}

type packageWriter struct {
	output repository.PackageResources
}

var _ kio.Writer = &packageWriter{}

func (w *packageWriter) Write(nodes []*yaml.RNode) error {
	paths := map[string][]*yaml.RNode{}
	for _, node := range nodes {
		path := getPath(node)
		paths[path] = append(paths[path], node)
	}

	// TODO: write directly into the package resources abstraction.
	// For now serializing into memory.
	buf := &bytes.Buffer{}
	for path, nodes := range paths {
		bw := kio.ByteWriter{
			Writer: buf,
			ClearAnnotations: []string{
				kioutil.PathAnnotation,
				kioutil.LegacyPathAnnotation,
			},
		}
		if err := bw.Write(nodes); err != nil {
			return err
		}
		w.output.Contents[path] = buf.String()
		buf.Reset()
	}
	return nil
}

func getPath(node *yaml.RNode) string {
	ann := node.GetAnnotations()
	if path, ok := ann[kioutil.PathAnnotation]; ok {
		return path
	}
	ns := node.GetNamespace()
	if ns == "" {
		ns = "non-namespaced"
	}
	name := node.GetName()
	if name == "" {
		name = "unnamed"
	}
	// TODO: harden for escaping etc.
	return path.Join(ns, fmt.Sprintf("%s.yaml", name))
}

type NodeToMapWriter struct {
	Resources map[string]string
}


text:
set -exo pipefail

util/commit-validator/validate-dco

util/commit-validator/validate-gofmt

bats script/test

export PGHOST=/var/run/postgresql
sudo service postgresql start

make test-unit-root

sudo service postgresql stop


text:
import os

from xml.dom import minidom, Node
from django.conf import settings

from api.tests.test_api import TestAPICase
from api.views import XFormViewSet

class TestFormsAPI(TestAPICase):
    def setUp(self):
        super(TestFormsAPI, self).setUp()
        self.view = XFormViewSet.as_view({
            'get': 'list',
        })

    def test_form_list(self):
        self._publish_xls_form_to_project()
        request = self.factory.get('/', **self.extra)
        response = self.view(request)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, [self.form_data])

    def test_form_list_other_user_access(self):
        """Test that a different user has no access to bob's form"""
        self._publish_xls_form_to_project()
        request = self.factory.get('/', **self.extra)
        response = self.view(request, owner=self.user.username)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, [self.form_data])

        # test with different user
        previous_user = self.user
        alice_data = {'username': 'alice', 'email': 'alice@localhost.com'}
        self._login_user_and_profile(extra_post_data=alice_data)
        self.assertEqual(self.user.username, 'alice')
        self.assertNotEqual(previous_user,  self.user)
        request = self.factory.get('/', **self.extra)
        response = self.view(request, owner=previous_user.username)
        self.assertEqual(response.status_code, 200)
        # should be empty
        self.assertEqual(response.data, [])

        # make form public
        xform = previous_user.xforms.get(id_string=self.form_data['id_string'])
        xform.shared = True
        xform.save()
        xform = previous_user.xforms.get(id_string=self.form_data['id_string'])
        self.form_data['public'] = True
        self.form_data['date_modified'] = xform.date_modified
        response = self.view(request, owner=previous_user.username)
        self.assertEqual(response.status_code, 200)

        # other user has access to public form
        self.assertEqual(response.data, [self.form_data])

    def test_form_get(self):
        self._publish_xls_form_to_project()
        view = XFormViewSet.as_view({
            'get': 'retrieve'
        })
        formid = self.xform.pk
        request = self.factory.get('/', **self.extra)
        response = view(request)
        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.data,
                         {'detail': 'Expected URL keyword argument `owner`.'})
        request = self.factory.get('/', **self.extra)
        response = view(request, owner='bob', pk=formid)
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, self.form_data)

    def test_form_format(self):
        self._publish_xls_form_to_project()
        view = XFormViewSet.as_view({
            'get': 'form'
        })
        formid = self.xform.pk
        data = {
            "title": "transportation_2011_07_25",
            "default_language": "default",
            "id_string": "transportation_2011_07_25",
            "type": "survey",
        }
        request = self.factory.get('/', **self.extra)
        response = view(request, owner='bob', pk=formid, format='json')
        self.assertEqual(response.status_code, 200)
        self.assertDictContainsSubset(data, response.data)
        self.assertRegexpMatches(response.data['name'], r'^transportation.*')

        tmpName = response.data['name']

        response = view(request, owner='bob', pk=formid, format='xml')
        self.assertEqual(response.status_code, 200)
        response_doc = minidom.parseString(response.data)

        xml_path = os.path.join(
            settings.PROJECT_ROOT, "main", "tests", "fixtures",
            "transportation", "transportation.xml")
        with open(xml_path) as xml_file:
            expected_doc = minidom.parse(xml_file)

        model_node = [
            n for n in
            response_doc.getElementsByTagName("h:head")[0].childNodes
            if n.nodeType == Node.ELEMENT_NODE and
            n.tagName == "model"][0]

        # check for UUID and remove
        uuid_nodes = [
            node for node in model_node.childNodes
            if node.nodeType == Node.ELEMENT_NODE
            and node.getAttribute("nodeset") == "/"+tmpName+"/formhub/uuid"]
        self.assertEqual(len(uuid_nodes), 1)
        uuid_node = uuid_nodes[0]
        uuid_node.setAttribute("calculate", "''")

        # check content without UUID
        self.assertEqual(response_doc.toxml().replace(tmpName, "transportation") , expected_doc.toxml())

    def test_form_tags(self):
        self._publish_xls_form_to_project()
        view = XFormViewSet.as_view({
            'get': 'labels',
            'post': 'labels',
            'delete': 'labels'
        })
        formid = self.xform.pk
        # no tags
        request = self.factory.get('/', **self.extra)
        response = view(request, owner='bob', pk=formid)
        self.assertEqual(response.data, [])
        # add tag "hello"
        request = self.factory.post('/', data={"tags": "hello"}, **self.extra)
        response = view(request, owner='bob', pk=formid)
        self.assertEqual(response.status_code, 201)
        self.assertEqual(response.data, [u'hello'])
        # remove tag "hello"
        request = self.factory.delete('/', data={"tags": "hello"},
                                      **self.extra)
        response = view(request, owner='bob', pk=formid, label='hello')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, [])


text:
package com.netflix.spinnaker.halyard.cli.command.v1.config;

import com.beust.jcommander.Parameters;
import com.netflix.spinnaker.halyard.cli.command.v1.config.persistentStorage.EditPersistentStorageCommand;
import com.netflix.spinnaker.halyard.cli.command.v1.config.persistentStorage.azs.AzsCommand;
import com.netflix.spinnaker.halyard.cli.command.v1.config.persistentStorage.gcs.GcsCommand;
import com.netflix.spinnaker.halyard.cli.command.v1.config.persistentStorage.oracle.OracleCommand;
import com.netflix.spinnaker.halyard.cli.command.v1.config.persistentStorage.s3.S3Command;
import com.netflix.spinnaker.halyard.cli.services.v1.Daemon;
import com.netflix.spinnaker.halyard.cli.services.v1.OperationHandler;
import com.netflix.spinnaker.halyard.cli.ui.v1.AnsiFormatUtils;
import com.netflix.spinnaker.halyard.config.model.v1.node.PersistentStorage;
import lombok.AccessLevel;
import lombok.Getter;

@Parameters(separators = "=")
public class PersistentStorageCommand extends AbstractConfigCommand {
  @Getter(AccessLevel.PUBLIC)
  private String commandName = "storage";

  @Getter(AccessLevel.PUBLIC)
  private String shortDescription = "Show Spinnaker's persistent storage configuration.";

  public PersistentStorageCommand() {
    registerSubcommand(new GcsCommand());
    registerSubcommand(new S3Command());
    registerSubcommand(new AzsCommand());
    registerSubcommand(new OracleCommand());
    registerSubcommand(new EditPersistentStorageCommand());
  }

  @Override
  protected void executeThis() {
    String currentDeployment = getCurrentDeployment();

    new OperationHandler<PersistentStorage>()
        .setOperation(Daemon.getPersistentStorage(currentDeployment, !noValidate))
        .setFailureMesssage("Failed to load persistent storage.")
        .setSuccessMessage("Configured persistent storage: ")
        .setFormat(AnsiFormatUtils.Format.STRING)
        .setUserFormatted(true)
        .get();
  }
}


text:
/*
package org.indiarose.backend.view;

import java.io.File;

import org.indiarose.lib.AppData;
import org.indiarose.lib.PathData;
import org.indiarose.backend.R;
import org.indiarose.backend.ScreenManager;
import org.indiarose.backend.view.element.AbstractScreen;
import org.indiarose.backend.view.element.ButtonItem;
import org.indiarose.lib.model.Category;
import org.indiarose.lib.model.Indiagram;
import org.indiarose.lib.utils.ImageManager;

import storm.communication.Mapper;
import storm.communication.MapperException;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ViewIndiagram extends AbstractScreen
{
	protected static final String LISTEN = "listen";
	protected static final String BACK = "back";
	protected static final String EDIT = "edit";
	protected static final String DELETE = "delete";

	protected Indiagram m_indiagram = null;
	protected LinearLayout m_layout = null;

	protected TextView m_indiagramText = null;
	protected TextView m_indiagramSound = null;
	protected TextView m_indiagramCategory = null;

	protected ImageView m_indiagramImage = null;
	protected LinearLayout m_indiagramTextColor = null;

	protected AlertDialog m_currentDialog = null;

	protected LinearLayout colorLayout = null;

	public ViewIndiagram(ScreenManager _screen, Indiagram _indiagram)
	{
		super(_screen);

		this.m_indiagram = _indiagram;

		m_indiagramText = new TextView(AppData.currentContext);
		m_indiagramSound = new TextView(AppData.currentContext);
		m_indiagramCategory = new TextView(AppData.currentContext);
		m_indiagramImage = new ImageView(AppData.currentContext);
		m_indiagramImage.setScaleType(ScaleType.CENTER_INSIDE);
		m_indiagramImage.setMaxHeight(AppData.settings.indiagramSize);
		m_indiagramImage.setMaxWidth(AppData.settings.indiagramSize);
		m_indiagramImage.setMinimumHeight(AppData.settings.indiagramSize);
		m_indiagramImage.setMinimumWidth(AppData.settings.indiagramSize);

		ButtonItem listenButton = new ButtonItem(AppData.currentContext, LISTEN);
		ButtonItem backButton = new ButtonItem(AppData.currentContext, BACK);
		ButtonItem editButton = new ButtonItem(AppData.currentContext, EDIT);
		ButtonItem deleteButton = new ButtonItem(AppData.currentContext, DELETE);

		listenButton.setText(R.string.listenButton);
		backButton.setText(R.string.backText);
		editButton.setText(R.string.editText);
		deleteButton.setText(R.string.deleteText);

		TextView [] views = new TextView[]{
				m_indiagramText, m_indiagramSound, m_indiagramCategory,
				listenButton, backButton, editButton, deleteButton
		};
		for(TextView v : views)
		{
			v.setTextSize(ScreenManager.fontSize);

			if(v instanceof ButtonItem)
			{
				v.setTextColor(Color.BLACK);
				try
				{
					Mapper.connect(v, "clicked", this, "buttonEvent");
				}
				catch(MapperException e)
				{
					Log.wtf("ViewIndiagram", "unable to connect button", e);
				}
			}
			else
			{
				v.setTextColor(Color.LTGRAY);
			}
		}

		LinearLayout leftPart = new LinearLayout(AppData.currentContext);
		leftPart.setOrientation(LinearLayout.VERTICAL);
		leftPart.setGravity(Gravity.CENTER);
		leftPart.setMinimumHeight(this.m_screen.getHeight());
		leftPart.setMinimumWidth(this.m_screen.getWidth() / 2);

		LinearLayout buttonLayout = new LinearLayout(AppData.currentContext);
		buttonLayout.setOrientation(LinearLayout.HORIZONTAL);
		buttonLayout.addView(backButton);
		buttonLayout.addView(editButton);
		buttonLayout.addView(deleteButton);

		leftPart.addView(m_indiagramText, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		leftPart.addView(m_indiagramCategory, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		leftPart.addView(m_indiagramSound, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		leftPart.addView(listenButton, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
		leftPart.addView(buttonLayout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));

		LinearLayout rightPart = new LinearLayout(AppData.currentContext);
		rightPart.setOrientation(LinearLayout.VERTICAL);
		rightPart.setGravity(Gravity.CENTER);
		rightPart.setMinimumHeight(this.m_screen.getHeight());
		rightPart.setMinimumWidth(this.m_screen.getWidth() / 2);

		rightPart.addView(m_indiagramImage);

		m_indiagramTextColor = new LinearLayout(AppData.currentContext);
		TextView textColorLabel = new TextView(AppData.currentContext);

		textColorLabel.setTextSize(ScreenManager.fontSize);
		textColorLabel.setText(R.string.indiagramTextColorLabel);
		textColorLabel.setTextColor(Color.LTGRAY);

		m_indiagramTextColor.setMinimumHeight(25);
		m_indiagramTextColor.setMinimumWidth(50);

		LinearLayout fakeLayout = new LinearLayout(AppData.currentContext);
		fakeLayout.setMinimumHeight(25);
		fakeLayout.setMinimumWidth(100);
		fakeLayout.setGravity(Gravity.CENTER);
		fakeLayout.addView(m_indiagramTextColor);

		colorLayout = new LinearLayout(AppData.currentContext);
		colorLayout.setOrientation(LinearLayout.HORIZONTAL);
		colorLayout.setGravity(Gravity.CENTER);
		colorLayout.addView(textColorLabel);
		colorLayout.addView(fakeLayout);

		rightPart.addView(colorLayout);

		m_layout = new LinearLayout(AppData.currentContext);
		m_layout.setOrientation(LinearLayout.HORIZONTAL);
		m_layout.addView(leftPart);
		m_layout.addView(rightPart);
	}

	@Override
	public View getView()
	{
		return m_layout;
	}

	@Override
	public void onPush()
	{
		refresh();
	}

	protected void refresh()
	{
		m_indiagramText.setText(AppData.currentContext.getString(R.string.indiagramTextLabel) + " " + m_indiagram.text);
		if(TextUtils.isEmpty(m_indiagram.soundPath))
		{
			m_indiagramSound.setText(AppData.currentContext.getString(R.string.indiagramSoundLabel) + " " + AppData.currentContext.getString(R.string.indiagramNoSound));
		}
		else
		{
			m_indiagramSound.setText(AppData.currentContext.getString(R.string.indiagramSoundLabel) + " " + m_indiagram.soundPath);
		}
		m_indiagramCategory.setText(AppData.currentContext.getString(R.string.indiagramCategoryLabel) + " " + Indiagram.getParent(m_indiagram).text);

		try
		{
			m_indiagramImage.setImageBitmap(ImageManager.loadImage(PathData.IMAGE_DIRECTORY + this.m_indiagram.imagePath, AppData.settings.indiagramSize, AppData.settings.indiagramSize));
		}
		catch (Exception e)
		{
			Log.wtf("ViewIndiagram", "unable to load image : " + this.m_indiagram.imagePath, e);
		}

		if(m_indiagram instanceof Category)
		{
			colorLayout.setVisibility(LinearLayout.VISIBLE);
			m_indiagramTextColor.setBackgroundColor(((Category)m_indiagram).textColor);
		}
		else
		{
			colorLayout.setVisibility(LinearLayout.GONE);
		}
	}

	public void buttonEvent(ButtonItem _button)
	{
		String id = _button.getIdentifier();
		if(id.equals(LISTEN))
		{
			ScreenManager.voiceReader.read(this.m_indiagram);
		}
		else if(id.equals(BACK))
		{
			this.m_screen.pop();
		}
		else if(id.equals(DELETE))
		{
			boolean ok = true;
			if(this.m_indiagram instanceof Category)
			{
				if(((Category) this.m_indiagram).indiagrams.size() > 0)
				{
					Toast.makeText(AppData.currentContext, R.string.canNotDeleteCategory, Toast.LENGTH_LONG).show();
					ok = false;
				}
			}

			if(ok)
			{
				AlertDialog.Builder adb = new AlertDialog.Builder(AppData.currentContext);

				adb.setTitle(R.string.deleteQuestion);
				adb.setIcon(android.R.drawable.ic_dialog_alert);
				adb.setPositiveButton(R.string.okText, new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface _dialog, int _which)
					{
						delete(m_indiagram);
						m_screen.pop();
					}
				});
				adb.setNegativeButton(R.string.cancelText, new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface _dialog, int _which)
					{
						closeDialog();
					}
				});

				adb.setOnCancelListener(new DialogInterface.OnCancelListener()
				{
					public void onCancel(DialogInterface _dialog)
					{
						closeDialog();
					}
				});
				this.m_currentDialog = adb.show();
			}
		}
		else if(id.equals(EDIT))
		{
			EditIndiagram edit = new EditIndiagram(this.m_screen, this.m_indiagram);
			try
			{
				Mapper.connect(edit, "indiagramChanged", this, "changeIndiagram");
			}
			catch (MapperException e)
			{
				Log.wtf("ViewIndiagram", "unable to connect edit screen", e);
			}
			this.m_screen.push(edit);
		}
	}

	public void changeIndiagram(Indiagram _indiagram)
	{
		this.m_indiagram = _indiagram;
	}

	protected void closeDialog()
	{
		this.m_currentDialog.dismiss();
	}

	protected void delete(Indiagram _indiagram)
	{
		AppData.changeLog.deleteIndiagram(_indiagram);
		//find parent and delete category
		Indiagram parent = Indiagram.getParent(_indiagram);
		if(parent != null)
		{
			AppData.changeLog.changeIndiagram(parent);
			((Category)parent).indiagrams.remove(_indiagram);
		}

		File f = new File(PathData.XML_DIRECTORY + _indiagram.filePath);
		f.delete();

		try
		{
			AppData.SaveHomeCategory();
		}
		catch (Exception e)
		{
			Log.wtf("ViewIndiagram", "Unable to save collection", e);
		}
	}
}
*/


text:
package ca.uhn.fhir.jpa.dao.data;

import ca.uhn.fhir.jpa.model.entity.ResourceIndexedSearchParamString;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface IResourceIndexedSearchParamStringDao extends JpaRepository<ResourceIndexedSearchParamString, Long> {

	@Modifying
	@Query("DELETE FROM ResourceIndexedSearchParamString t WHERE t.myResourcePid = :resId")
	void deleteByResourceId(@Param("resId") Long theResourcePid);

	@Query("SELECT t FROM ResourceIndexedSearchParamString t WHERE t.myResourcePid = :resId")
	List<ResourceIndexedSearchParamString> findAllForResourceId(@Param("resId") Long thePatientId);
}


text:
This is a little daemon which monitors average site response time in New
Relic, then plays sounds if it goes above predefined thresholds. It's smart
enough to only play sounds once, each time things get worse, so that you're
not constantly bombarded with sirens.

This is just a simple first draft where the thresholds are hard-coded in
main.go, but it works and is being used in production.

## Installation

Just `go install` like any other go program!

For Linux users, I've included a sample systemd service script which you
can use to run it at startup.

For sound output, it requires that the `sox` library be installed such that
the `play` command exists in its PATH. (On some systems, you may also need
to install the `libsox-fmt-mp3` library to get MP3 playback.)

## Configuration

The config file looks like:

```
# No, these are not real credentials.
ApiKey = "e49524050d4b8e04f4d0e886b82921d74e58f05169105de"
ApplicationId = "2031337"
SoundsDir = "/home/fimmtiu/go/src/github.com/fimmtiu/red-alert/sounds"
```

It knows the following variables:

**ApiKey** (string)

Your New Relic API key. No default, obviously; must be provided.

**ApplicationId** (string)

Your New Relic application ID. No default, obviously; must be provided.

**DurationForAverage** (unsigned integer)

The "average response time" value will be calculated based on the response
times from the past `DurationForAverage` seconds. Defaults to 300 seconds
(5 minutes).

**PollingInterval** (unsigned integer)

The time between calls, in seconds, to the New Relic API to fetch the response time.
Defaults to 30 seconds.

**SoundsDir** (string)

The directory containing the sound files. Defaults to the directory the
daemon was started in.

**VolumeAdjustment** (integer)

The adjustment, in positive or negative decibels, to apply to the sound
files during playback. Defaults to 0 (no adjustment).


text:
package milkyway.SaveableSerializing.ItemStacks.Upper_1_7.ItemData.ItemMetas;

import milkyway.SaveableSerializing.ItemStacks.Upper_1_7.DataTypes.ListSaveable;
import milkyway.SaveableSerializing.Parser.SaveableData;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Developer_Unlocated on 2017-04-17.
 */
public class SaveableBookMeta extends SubMeta {
    List<String> page = new ArrayList<>();
    String author = "Mr.Minecraft";
    @Override
    public void writeBy(StringBuilder builder) {
        builder.append(author).append("\n");
        new ListSaveable(page).appendSubSet(builder);
    }

    @Override
    public void appendTo(List<String> builded) {
        if(builded.size() >= 1)
            author = builded.get(0);
    }

    @Override
    public String getName() {
        return "SubMeta-BookMeta";
    }

    @Override
    public void appendObject(String str, SaveableData data) {
        if(str.equals("List"))
            page = ((ListSaveable)data).data;
    }

    @Override
    public SaveableData getNewInstance() {
        return new SaveableBookMeta();
    }

    @Override
    public void setTo(ItemMeta meta) {
        if(meta instanceof BookMeta){
            BookMeta metaSub = (BookMeta) meta;
            metaSub.setAuthor(author);
            metaSub.setPages(page);
        }
    }

    @Override
    public SubMeta setFrom(ItemMeta meta) {
        if(meta instanceof BookMeta)
        {
            BookMeta metaSub = (BookMeta) meta;
            author = metaSub.getAuthor();
            page = metaSub.getPages();
        }
        return this;
    }
}


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Taskrouter\V1\Workspace\TaskQueue;

use Twilio\Options;
use Twilio\Values;

abstract class TaskQueueStatisticsOptions {
    /**
     * @param \DateTime $endDate The end_date
     * @param integer $minutes The minutes
     * @param \DateTime $startDate The start_date
     * @return FetchTaskQueueStatisticsOptions Options builder
     */
    public static function fetch($endDate = Values::NONE, $minutes = Values::NONE, $startDate = Values::NONE) {
        return new FetchTaskQueueStatisticsOptions($endDate, $minutes, $startDate);
    }
}

class FetchTaskQueueStatisticsOptions extends Options {
    /**
     * @param \DateTime $endDate The end_date
     * @param integer $minutes The minutes
     * @param \DateTime $startDate The start_date
     */
    public function __construct($endDate = Values::NONE, $minutes = Values::NONE, $startDate = Values::NONE) {
        $this->options['endDate'] = $endDate;
        $this->options['minutes'] = $minutes;
        $this->options['startDate'] = $startDate;
    }

    /**
     * The end_date
     *
     * @param \DateTime $endDate The end_date
     * @return $this Fluent Builder
     */
    public function setEndDate($endDate) {
        $this->options['endDate'] = $endDate;
        return $this;
    }

    /**
     * The minutes
     *
     * @param integer $minutes The minutes
     * @return $this Fluent Builder
     */
    public function setMinutes($minutes) {
        $this->options['minutes'] = $minutes;
        return $this;
    }

    /**
     * The start_date
     *
     * @param \DateTime $startDate The start_date
     * @return $this Fluent Builder
     */
    public function setStartDate($startDate) {
        $this->options['startDate'] = $startDate;
        return $this;
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        $options = array();
        foreach ($this->options as $key => $value) {
            if ($value != Values::NONE) {
                $options[] = "$key=$value";
            }
        }
        return '[Twilio.Taskrouter.V1.FetchTaskQueueStatisticsOptions ' . implode(' ', $options) . ']';
    }
}


text:
class CreateCourses < ActiveRecord::Migration[5.1]
  def change
    create_table :courses do |t|
      t.string :name
      t.integer :enrollment

      t.timestamps
    end
  end
end


text:
<!DOCTYPE html>

		<title>Arby 'n' The Chief - SensCritique</title>

				<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
							<meta name="description" content="Cette série met en scène deux figurines, Master Chief et l'Arbiter de la série Halo, qui prennent vie lorsque leur propriétaire, Jon, quitte l'appartement...." />
									<meta property="og:image" content="http://media.senscritique.com/media/000006567279/1200/Arby_n_The_Chief.jpg" />

		<link rel="publisher" href="https://plus.google.com/+senscritique">

		<link rel="apple-touch-icon" sizes="57x57" href="http://static.senscritique.com/img/favicon/apple-touch-icon-57x57.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="60x60" href="http://static.senscritique.com/img/favicon/apple-touch-icon-60x60.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="72x72" href="http://static.senscritique.com/img/favicon/apple-touch-icon-72x72.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="76x76" href="http://static.senscritique.com/img/favicon/apple-touch-icon-76x76.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="114x114" href="http://static.senscritique.com/img/favicon/apple-touch-icon-114x114.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="120x120" href="http://static.senscritique.com/img/favicon/apple-touch-icon-120x120.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="144x144" href="http://static.senscritique.com/img/favicon/apple-touch-icon-144x144.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="152x152" href="http://static.senscritique.com/img/favicon/apple-touch-icon-152x152.png?v=eELP384vde">
		<link rel="apple-touch-icon" sizes="180x180" href="http://static.senscritique.com/img/favicon/apple-touch-icon-180x180.png?v=eELP384vde">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/favicon-32x32.png?v=eELP384vde" sizes="32x32">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/favicon-194x194.png?v=eELP384vde" sizes="194x194">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/favicon-96x96.png?v=eELP384vde" sizes="96x96">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/android-chrome-192x192.png?v=eELP384vde" sizes="192x192">
		<link rel="icon" type="image/png" href="http://static.senscritique.com/img/favicon/favicon-16x16.png?v=eELP384vde" sizes="16x16">
		<link rel="manifest" href="http://static.senscritique.com/img/favicon/manifest.json?v=eELP384vde">
		<link rel="shortcut icon" href="http://static.senscritique.com/img/favicon/favicon.ico?v=eELP384vde">

						<link rel="stylesheet" type="text/css" href="http://static.senscritique.com/lib/optimized_ln/fdf8f64f5bf9f78145e6a2b51f1dd63f.css"/>

	<link rel="stylesheet" type="text/css" href="http://static.senscritique.com/lib/optimized_ln/6562849bc59530395bda23a76097149f.css"/>

		<link rel="apple-touch-icon" href="/img/favicon/57.png">
		<link rel="apple-touch-icon" sizes="72x72" href="/img/favicon/72.png">
		<link rel="apple-touch-icon" sizes="114x114" href="/img/favicon/114.png">
		<link rel="publisher" href="https://plus.google.com/+senscritique">

							<button type="button" data-rel="btn-register" data-scmodal-type="login" class="d-link-alt">Déjà inscrit</button> ?
							<form action="/" method="POST" class="lahe-userSubmenu lahe-signin" data-rel="sc-headerSignin">

Connectez-vous avec

								Facebook
								Twitter

ou

								<input type="text" class="lahe-signin-field" name="email" placeholder="Adresse email" data-rel="sc-headerSignin-email" />
								<input type="password" class="lahe-signin-field" name="password" placeholder="Mot de passe" data-rel="sc-headerSignin-password" />
								Mot de passe oublié ?
								<fieldset class="lahe-signin-clear">

									<input type="submit" class="d-button lahe-signin-confirm" value="Connexion" />
								</fieldset>
							</form>

						<button type="button" data-rel="btn-register" data-scmodal-type="register" class="lahe-userMenu-connect">Créer mon compte</button>

					SensCritique

							Films

Au cinéma

																																														Sorties de la semaine
															À l'affiche
															Mes cinémas
															Meilleurs films 2015

TV / VOD

																																														EveryMovie
															A la télé
															En VOD

Guide

																																														Vos films préférés
															Top 111 films
															Sondages

							Séries

Actualité

																																														Séries du moment
															Meilleures séries 2015

Guide

																																														Vos séries préférées
															Top 111 séries
															Sondages

							Jeux

Actualité

																																														Jeux du moment
															Agenda
															Jeux les plus attendus
															Meilleurs jeux 2015

Guide

																																														Vos jeux préférés
															Top 111 jeux
															Sondages

							Livres

Actualité

																																														Livres du moment
															Meilleures ventes
															Meilleurs livres 2015
															Prix littéraires 2014

Guide

																																														Vos livres préférés
															Top 111 livres
															Sondages

							BD

Actualité

																																														Franco-belge
															Comics
															Mangas
															Meilleures BD 2015

Guide

																																														Vos BD préférées
															Top 111 BD
															Sondages

							Musique

Actualité

																																														Albums du moment
															Prochaines sorties
															Meilleurs albums 2015

Guide

																																														Vos albums préférés
															Top 111 albums
															Sondages

						Posts

			<form action="/recherche?" method="GET" class="lahe-searchBar-content" data-rel="sc-headerSearch">

					 Chercher une œuvre, un artiste, une liste, un cinéma ou un membre

						Tout

Tout

Films

Séries

Livres

BD

Jeux vidéo

Albums de musique

Morceaux de musique

Listes d'oeuvres

Sondages

Sagas

Artistes et sociétés

Membres

Cinémas

					<input type="text" name="query" value="" class="unfocus lahe-searchBar-query" data-rel="sc-headerSearch-query" />
					<button type="button" class="lahe-searchBar-close" data-rel="sc-headerSearch-close">

					</button>

			</form>

SensCritique

Séries

Action

Arby 'n' The Chief

							Arby 'n' The Chief

																								(2007)

12345678910

																															<button type="button" data-sc-action="current"
									data-sc-product-id="445599"
									data-sc-tooltip="true"
									title="Je suis cette série"
									class="d-button pvi-product-scaction ">

								En cours
							</button>

												<button type="button" data-sc-action="recommend"
								data-sc-product-id="445599"
								class="d-button pvi-product-scaction "
								style="display:none;">
							 Coup de coeur
						</button>
																			<button type="button" data-rel="bt-review sc-button-modal-sc"
									data-sc-product-id="445599"
									data-scmodal-type="review"
									class="d-button pvi-product-scaction"
									style="display:none;">
								 Critiquer
							</button>

												<button type="button" data-sc-action="wish-list"
								data-sc-product-id="445599"
								class="d-button pvi-product-scaction "
								>

								Envie de la voir

						</button>

												<button type="button" data-rel="sc-button"
								data-sc-product-id="445599"
								class="d-button pvi-product-contextmenu">

						</button>

							10
							1
							4
							0

0

0

0

0

0

0

0

2

2

0

					0

0

					1

					0

0

					2

					0

0

					3

					0

0

					4

					0

0

					5

					0

0

					6

					0

0

					7

					2

2

					8

					2

2

					9

					0

0

					10

									4

									1

									0

										0

					<button type="button" class="pco-social-action" data-rel="sc-share-tooltip" data-sc-product-id="445599">Partager</button>

					<button type="button" class="pco-social-action" data-rel="sc-buy-tooltip" data-sc-product-id="445599">Acheter</button>

					Accueil

				Casting

					Photos

Emission Web

					 de   DigitalPh33r et   Jon Graham

							Action,

							drame et

							comédie

					YouTube

					8 min

<time datetime="2007-10-12" >12 octobre 2007</time>

Cette série met en scène deux figurines, Master Chief et l'Arbiter de la série Halo, qui prennent vie lorsque leur propriétaire, Jon, quitte l'appartement.

Elle tourne principalement autour des deux jouant à Halo 3 ou faisant des choses en rapport avec Halo.

Master Chief: w/e. ur just 2 p00r 2...					<button type="button" class="d-link" data-rel="sc-btn-more-storyline" data-sc-product-id="445599">Lire la suite</button>

					<button type="button" class="d-link" data-rel="sc-btn-close-storyline" data-sc-product-id="445599">Fermer</button>

					PostsArby 'n' The Chief

				Vous avez une anecdote, une vidéo/photo ou une simple question sur cette série ?

				<button type="button" data-rel="js-link" data-sc-link="/post/445599" class="d-button-success-xl d-more pvi-emptyTopic-btn">
					Créer un post
				</button>
				<button type="button" data-rel="js-link" data-sc-link="/posts" class="d-button-xl d-more pvi-emptyTopic-btn">
					Tous les posts
				</button>

				IntervenantsArby 'n' The Chief

					Daniel Lazslo

					Jon Graham

					Microsoft Mary

					Microsoft Mike

					Microsoft Sam

			 Intervenants de l'émission Web Arby 'n' The Chief

				InfosArby 'n' The Chief

										Scénaristes

								Jon Graham

										Producteurs

								Jon Graham

				Dernières actions sur cette émission Web

			Arby 'n' The Chief

		 Plus d'actualité

				Le bouche à oreille

L'avis de vos amis en 1 clic

				S'inscrire avec FB

				Lab

				Changelog

				À propos

				Aide

				Blog

				Publicité

				Emploi

				Conditions d'utilisation

Séances de cinéma

Programme TV ce soir

Programme TV aujourd'hui

Programme TV demain

Programme TV cette semaine

					Avis films

					Avis séries

					Avis livres

					Avis BD

					Avis jeux vidéo

					Avis musique

		© 2015 SensCritique