text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cannon.prod.dal.mapper.Student">
	<resultMap type="Student" id="StudentResultMap">
		<id property="no" column="no" />
		<result property="name" column="name" />
		<result property="sex" column="sex" />
	</resultMap>
	<!-- 查询学生,根据id -->
	<select id="getByNo" parameterType="String" resultType="Student">
        <![CDATA[
            SELECT * FROM `t_student` WHERE `no` = #{no}
        ]]>
	</select>

	<select id="getByTable" resultType="Student">
        <![CDATA[
            SELECT * FROM `t_student`
        ]]>
	</select>

	<delete id="deleteByNo" parameterType="String">
		<![CDATA[
            DELETE FROM `t_student` WHERE `no` = #{no}
        ]]>
	</delete>
	<insert id="create" parameterType="Student">
		INSERT INTO t_student(no,
		name, sex) VALUES(#{no}, #{name}, #{sex})
	</insert>
	<update id="update" parameterType="Student">
		UPDATE t_student
		<trim prefix="SET" suffixOverrides=",">
			<if test="name != null">name=#{name},</if>
		</trim>
		WHERE no=#{no}
	</update>
</mapper>


text:
package io.novaordis.gld.api.todiscard;

import org.slf4j.Logger;
import org.junit.Test;
import org.slf4j.LoggerFactory;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class NodeTest
{
    // Constants -------------------------------------------------------------------------------------------------------

    private static final Logger log = LoggerFactory.getLogger(NodeTest.class);

    // Static ----------------------------------------------------------------------------------------------------------

    // Attributes ------------------------------------------------------------------------------------------------------

    // Constructors ----------------------------------------------------------------------------------------------------

    // Public ----------------------------------------------------------------------------------------------------------

    @Test
    public void embeddedUppercase() throws Exception
    {
        List<Node> nl = Node.toNodeList("EMBEDDED");
        assertEquals(1, nl.size());
        assertTrue(nl.get(0) instanceof EmbeddedNode);
    }

    @Test
    public void embeddedLowercase() throws Exception
    {
        List<Node> nl = Node.toNodeList("embedded");
        assertEquals(1, nl.size());
        assertTrue(nl.get(0) instanceof EmbeddedNode);
    }

    @Test
    public void embeddedWithPortThatWillBeIgnored() throws Exception
    {
        List<Node> nl = Node.toNodeList("embedded:10001");
        assertEquals(1, nl.size());
        Node n = nl.get(0);
        assertTrue(n instanceof EmbeddedNode);
        assertEquals(0, n.getPort());
    }

    @Test
    public void embeddedWithPortThatWillBeIgnored2() throws Exception
    {
        List<Node> nl = Node.toNodeList("embedded:10001,localhost:10002");
        assertEquals(2, nl.size());

        Node n = nl.get(0);
        assertTrue(n instanceof EmbeddedNode);
        assertEquals(0, n.getPort());

        Node n2 = nl.get(1);
        assertEquals("localhost", n2.getHost());
        assertEquals(10002, n2.getPort());
    }

    @Test
    public void embedded_PrePopulated() throws Exception
    {
        List<Node> nl = Node.toNodeList("embedded[5]");
        assertEquals(1, nl.size());

        EmbeddedNode n = (EmbeddedNode)nl.get(0);

        assertEquals(5, n.getCapacity());
    }

    // Package protected -----------------------------------------------------------------------------------------------

    // Protected -------------------------------------------------------------------------------------------------------

    // Private ---------------------------------------------------------------------------------------------------------

    // Inner classes ---------------------------------------------------------------------------------------------------

}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/route53domains/Route53Domains_EXPORTS.h>
#include <aws/route53domains/Route53DomainsRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Route53Domains
{
namespace Model
{

  /**
   */
  class AWS_ROUTE53DOMAINS_API GetContactReachabilityStatusRequest : public Route53DomainsRequest
  {
  public:
    GetContactReachabilityStatusRequest();
    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The name of the domain for which you want to know whether the registrant
     * contact has confirmed that the email address is valid.

Type: String

     *
Default: None

Required: Yes

     */
    inline const Aws::String& GetDomainName() const{ return m_domainName; }

    /**
     *
The name of the domain for which you want to know whether the registrant
     * contact has confirmed that the email address is valid.

Type: String

     *
Default: None

Required: Yes

     */
    inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    /**
     *
The name of the domain for which you want to know whether the registrant
     * contact has confirmed that the email address is valid.

Type: String

     *
Default: None

Required: Yes

     */
    inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = value; }

    /**
     *
The name of the domain for which you want to know whether the registrant
     * contact has confirmed that the email address is valid.

Type: String

     *
Default: None

Required: Yes

     */
    inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); }

    /**
     *
The name of the domain for which you want to know whether the registrant
     * contact has confirmed that the email address is valid.

Type: String

     *
Default: None

Required: Yes

     */
    inline GetContactReachabilityStatusRequest& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}

    /**
     *
The name of the domain for which you want to know whether the registrant
     * contact has confirmed that the email address is valid.

Type: String

     *
Default: None

Required: Yes

     */
    inline GetContactReachabilityStatusRequest& WithDomainName(Aws::String&& value) { SetDomainName(value); return *this;}

    /**
     *
The name of the domain for which you want to know whether the registrant
     * contact has confirmed that the email address is valid.

Type: String

     *
Default: None

Required: Yes

     */
    inline GetContactReachabilityStatusRequest& WithDomainName(const char* value) { SetDomainName(value); return *this;}

  private:
    Aws::String m_domainName;
    bool m_domainNameHasBeenSet;
  };

} // namespace Model
} // namespace Route53Domains
} // namespace Aws


text:
import sys, os, time
import shutil
import tempfile
import subprocess
thisPath = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.abspath(os.path.join(thisPath,"../../")))
import Utils.STFormat.STTools as ST
import Utils.STFormat.ConvertXML as STConvert
import Utils.InteractionXML.RemoveUnconnectedEntities
import Utils.InteractionXML.DivideSets
import Utils.Download
import Utils.ProteinNameSplitter as ProteinNameSplitter
import Utils.Settings as Settings
import Utils.Stream as Stream
import Utils.FindHeads as FindHeads
import Tools.SentenceSplitter
import Tools.BLLIPParser
import Tools.StanfordParser
#import Utils.InteractionXML.CopyParse
try:
    import cElementTree as ET
except ImportError:
    import xml.etree.cElementTree as ET
import Utils.ElementTreeUtils as ETUtils
from collections import defaultdict
import Utils.Range as Range
import DDITools

def getSets(popSize):
    random.seed(15)
    pop = range(popSize)
    random.shuffle(pop)
    floatPopSize = float(popSize)
    trainSet = set(pop[0:int(0.5 * floatPopSize)])
    develSet = set(pop[int(0.5 * floatPopSize):int(0.75 * floatPopSize)])
    testSet = set(pop[int(0.75 * floatPopSize):])
    assert len(trainSet) + len(develSet) + len(testSet) == popSize

    division = []
    for i in xrange(popSize):
        if i in trainSet:
            division.append("t")
        elif i in develSet:
            division.append("d")
        else:
            division.append("e")
    assert len(division) == popSize
    return division

def fixEntities(xml):
    counts = defaultdict(int)
    for sentence in xml.getiterator("sentence"):
        sText = sentence.get("text")
        for entity in sentence.findall("entity"):
            charOffset = entity.get("charOffset")
            if charOffset == "-":
                assert False, str(entity)
                sentence.remove(entity)
                counts["removed-invalid"] += 1
            else:
                charOffset = Range.charOffsetToSingleTuple(charOffset)
                # fix length
                realLength = len(entity.get("text"))
                lenDiff = (charOffset[1] - charOffset[0] + 1) - realLength
                if lenDiff != realLength:
                    counts["incorrect-ent-offset"] += 1
                    counts["incorrect-ent-offset-diff"+str(lenDiff)] += 1
                    if abs(lenDiff) > 2:
                        print "Warning, lenDiff:", (lenDiff, charOffset, sText, entity.get("text"), entity.get("id"))
                charOffset = (charOffset[0], charOffset[0] + realLength)
                # find starting position
                entIndex = sText.find(entity.get("text"), charOffset[0])
                if entIndex == -1:
                    for i in [-1,-2,-3]:
                        entIndex = sText.find(entity.get("text"), charOffset[0]+i)
                        if entIndex != -1:
                            break
                if entIndex != 0: # could be lowercase
                    sTextLower = sText.lower()
                    for i in [0,-1,-2,-3]:
                        lowerEntIndex = sTextLower.find(entity.get("text"), charOffset[0]+i)
                        if lowerEntIndex != -1:
                            break
                    if lowerEntIndex != -1 and abs(lowerEntIndex - charOffset[0]) < abs(entIndex - charOffset[0]):
                        entIndex = lowerEntIndex
                assert entIndex != -1, (charOffset, sText, entity.get("text"), entity.get("id"))
                indexDiff = entIndex - charOffset[0]
                if indexDiff != 0:
                    counts["incorrect-ent-index"] += 1
                    counts["incorrect-ent-index-diff"+str(indexDiff)] += 1
                    print "Warning, indexDiff:", (indexDiff, charOffset, sText, entity.get("text"), entity.get("id"))
                # move offset
                charOffset = (charOffset[0]+indexDiff, charOffset[1]+indexDiff)
                # validate new offset
                sEntity = sText[charOffset[0]:charOffset[1]]
                assert sEntity == entity.get("text") or sEntity.lower() == entity.get("text"), (charOffset, sText, entity.get("text"), entity.get("id"))
                entity.set("charOffset", Range.tuplesToCharOffset( (charOffset[0], charOffset[1])))
                entity.set("given", "True")
        for interaction in sentence.findall("interaction"):
            interaction.set("type", "DDI")
    print "Fix counts:", counts

def convertToInteractions(xml):
    print "Renaming pair-elements"
    counts = defaultdict(int)
    for sentence in xml.getiterator("sentence"):
        sentence.set("charOffset", "0-" + str(len(sentence.get("text"))) )
        for pair in sentence.findall("pair"):
            if pair.get("interaction") == "true":
                pair.tag = "interaction"
                pair.set("type", "DDI")
                counts["pos"] += 1
            else:
                sentence.remove(pair)
                counts["neg"] += 1
    print "Pair counts:", counts

def loadDocs(inDir, idStart=0):
    print "Loading documents from", inDir
    sentences = {"positive":[], "negative":[]}
    docCounts = {}
    docById = {}
    documents = []
    for filename in sorted(os.listdir(inDir)):
        if filename.endswith(".xml"):
            print "Reading", filename,
            xml = ETUtils.ETFromObj(os.path.join(inDir, filename))
            for document in xml.getiterator("document"):
                counts = [0,0]
                for sentence in document.findall("sentence"):
                    #sentence.set("document.get("origId") + "." + sentence.get("origId"))
                    truePairs = False
                    for pair in sentence.findall("pair"):
                        if pair.get("interaction") == "true":
                            truePairs = True
                            break
                    if truePairs:
                        counts[0] += 1
                        sentences["positive"].append(sentence)
                    else:
                        counts[1] += 1
                        sentences["negative"].append(sentence)
                assert document.get("id") not in docCounts
                docCounts[document.get("id")] = counts
                docById[document.get("id")] = document
                documents.append(document)
                print counts,
                #print ETUtils.toStr(document)
            print
    print "Positive sentences:", len(sentences["positive"])
    print "Negative sentences:", len(sentences["negative"])
    return documents, docById, docCounts

def convertDDI(outDir, downloadDir=None, redownload=False, makeIntermediateFiles=True, debug=False):
    cwd = os.getcwd()
    if not os.path.exists(outDir):
        os.makedirs(outDir)
    os.chdir(outDir)
    logFileName = os.path.join(outDir, "DDI11-conversion-log.txt")
    Stream.openLog(logFileName)
    print >> sys.stderr, "=======================", "Converting DDI'11 corpus", "======================="
    corpusDir = outDir + "/DDI11-original"
    Utils.Download.downloadAndExtract(Settings.URL["DDI11_CORPUS"], corpusDir, downloadDir)

    bigfileName = os.path.join(outDir, "DDI11")
    #oldXML = ETUtils.ETFromObj(bigfileName+".xml")
    trainUnified = corpusDir + "/train"
    trainMTMX = corpusDir + "/train_MTMX"
    testUnified = corpusDir + "/test"
    testMTMX = corpusDir + "/test_MTMX"

    # Load main documents
    tempdir = tempfile.mkdtemp()
    print >> sys.stderr, "Temporary files directory at", tempdir
    documents, docById, docCounts = loadDocs(trainUnified)
    # Divide training data into a train and devel set
    sortedDocCounts = sorted(docCounts.iteritems(), key=lambda (k,v): (v,k), reverse=True)
    datasetCounts = {"train":[0,0], "devel":[0,0], "test":[0,0]}
    for i in range(0, len(sortedDocCounts)-3, 4):
        for j in [0,1]:
            docById[sortedDocCounts[i+j][0]].set("set", "train")
            datasetCounts["train"][0] += sortedDocCounts[i+j][1][0]
            datasetCounts["train"][1] += sortedDocCounts[i+j][1][1]
        docById[sortedDocCounts[i+2][0]].set("set", "train") #docById[sortedDocCounts[i+2][0]].set("set", "devel")
        docById[sortedDocCounts[i+3][0]].set("set", "devel") #docById[sortedDocCounts[i+3][0]].set("set", "test")
        datasetCounts["train"][0] += sortedDocCounts[i+2][1][0] #datasetCounts["devel"][0] += sortedDocCounts[i+2][1][0]
        datasetCounts["train"][1] += sortedDocCounts[i+2][1][1] #datasetCounts["devel"][1] += sortedDocCounts[i+2][1][1]
        datasetCounts["devel"][0] += sortedDocCounts[i+3][1][0] #datasetCounts["test"][0] += sortedDocCounts[i+3][1][0]
        datasetCounts["devel"][1] += sortedDocCounts[i+3][1][1] #datasetCounts["test"][1] += sortedDocCounts[i+3][1][1]
    for document in documents: # epajaolliset jaa yli
        if document.get("set") == None:
            document.set("set", "train")
    # Print division results
    print >> sys.stderr, datasetCounts
    for key in datasetCounts.keys():
        if datasetCounts[key][1] != 0:
            print key, datasetCounts[key][0] / float(datasetCounts[key][1])
        else:
            print key, datasetCounts[key][0], "/", float(datasetCounts[key][1])
    # Some of the train and test ids overlap. Let's change the train set ids, because test set ones are needed
    # for the final evaluation.
    changeIdCount = 1000
    for trainId in ['DrugDDI.d312', 'DrugDDI.d316', 'DrugDDI.d332', 'DrugDDI.d334', 'DrugDDI.d337',
                    'DrugDDI.d342', 'DrugDDI.d349', 'DrugDDI.d354', 'DrugDDI.d373', 'DrugDDI.d379',
                    'DrugDDI.d383', 'DrugDDI.d388', 'DrugDDI.d392', 'DrugDDI.d396', 'DrugDDI.d398',
                    'DrugDDI.d409', 'DrugDDI.d411', 'DrugDDI.d415', 'DrugDDI.d425', 'DrugDDI.d430',
                    'DrugDDI.d433', 'DrugDDI.d448', 'DrugDDI.d450', 'DrugDDI.d452', 'DrugDDI.d462',
                    'DrugDDI.d467', 'DrugDDI.d470', 'DrugDDI.d474', 'DrugDDI.d480', 'DrugDDI.d482',
                    'DrugDDI.d485', 'DrugDDI.d492', 'DrugDDI.d494', 'DrugDDI.d496', 'DrugDDI.d498',
                    'DrugDDI.d500', 'DrugDDI.d503', 'DrugDDI.d506', 'DrugDDI.d518', 'DrugDDI.d523',
                    'DrugDDI.d528', 'DrugDDI.d535', 'DrugDDI.d539', 'DrugDDI.d552', 'DrugDDI.d554',
                    'DrugDDI.d558', 'DrugDDI.d561', 'DrugDDI.d570', 'DrugDDI.d578']:
        newId = "DrugDDI.d" + str(changeIdCount)
        print >> sys.stderr, "Changing train/devel id", trainId, "to", newId
        for element in docById[trainId].getiterator():
            for attrName, attrValue in element.attrib.iteritems():
                if trainId in attrValue:
                    element.set(attrName, attrValue.replace(trainId, newId))
        docById[newId] = docById[trainId]
        del docById[trainId]
        changeIdCount += 1
    # If test set exists, load it, too
    if testUnified != None:
        testDocuments, testDocById, testDocCounts = loadDocs(testUnified)
        for document in testDocuments:
            document.set("set", "test")
        documents = documents + testDocuments
        overlappingIds = []
        for key in docById:
            if key in testDocById:
                overlappingIds.append(key)
        for key in docById:
            assert key not in testDocById, (key, docById[key].get("origId"), testDocById[key].get("origId"), sorted(docById.keys()), sorted(testDocById.keys()), sorted(overlappingIds))
        docById.update(testDocById)

    # Add all documents into one XML
    xmlTree = ET.ElementTree(ET.Element("corpus"))
    root = xmlTree.getroot()
    root.set("source", "DDI11")
    for document in documents:
        root.append(document)
    if makeIntermediateFiles:
        ETUtils.write(root, bigfileName + "-documents-notfixed.xml")
    xml = xmlTree
    print >> sys.stderr, "Fixing DDI XML"
    fixEntities(xml)
    convertToInteractions(xml)
    # Add MTMX
    if trainMTMX != None:
        inDir = Utils.Download.getTopDir(tempdir, Utils.Download.downloadAndExtract(trainMTMX, tempdir, outDir + "/DDI11-original"))
        DDITools.addMTMX(xml, inDir)
    if testMTMX != None:
        inDir = Utils.Download.getTopDir(tempdir, Utils.Download.downloadAndExtract(testMTMX, tempdir, outDir + "/DDI11-original"))
        DDITools.addMTMX(xml, inDir)
    if makeIntermediateFiles:
        ETUtils.write(root, bigfileName + "-documents.xml")

    print >> sys.stderr, "---------------", "Inserting TEES-generated analyses", "---------------"
    Utils.Download.downloadAndExtract(Settings.URL["TEES_PARSES"], os.path.join(Settings.DATAPATH, "TEES-parses"), downloadDir, redownload=redownload)
    extractedFilename = os.path.join(Settings.DATAPATH, "TEES-parses") + "/DDI11"
    print >> sys.stderr, "Making sentences"
    Tools.SentenceSplitter.makeSentences(xml, extractedFilename, None)
    print >> sys.stderr, "Inserting McCC parses"
    Tools.BLLIPParser.insertParses(xml, extractedFilename, None, extraAttributes={"source":"TEES-preparsed"})
    print >> sys.stderr, "Inserting Stanford conversions"
    Tools.StanfordParser.insertParses(xml, extractedFilename, None, extraAttributes={"stanfordSource":"TEES-preparsed"})
    print >> sys.stderr, "Protein Name Splitting"
    splitTarget = "McCC"
    #ProteinNameSplitter.mainFunc(xml, None, splitTarget, splitTarget, "split-"+splitTarget, "split-"+splitTarget)
    ProteinNameSplitter.mainFunc(xml, None, splitTarget, removeOld=True)
    print >> sys.stderr, "Head Detection"
    #xml = FindHeads.findHeads(xml, "split-"+splitTarget, tokenization=None, output=None, removeExisting=True)
    xml = FindHeads.findHeads(xml, splitTarget, tokenization=None, output=None, removeExisting=True)

    print >> sys.stderr, "Dividing into sets"
    Utils.InteractionXML.DivideSets.processCorpus(xml, outDir, "DDI11", ".xml")

    Stream.closeLog(logFileName)
    if not debug:
        print >> sys.stderr, "Removing temporary directory", tempdir
        shutil.rmtree(tempdir)
    os.chdir(cwd)

if __name__=="__main__":
    # Import Psyco if available
    try:
        import psyco
        psyco.full()
        print >> sys.stderr, "Found Psyco, using"
    except ImportError:
        print >> sys.stderr, "Psyco not installed"

    from optparse import OptionParser
    from Utils.Parameters import *
    optparser = OptionParser(usage="%prog [options]\nDDI'11 Shared Task corpus conversion")
    optparser.add_option("-o", "--outdir", default=os.path.normpath(Settings.DATAPATH + "/corpora"), dest="outdir", help="directory for output files")
    optparser.add_option("-d", "--downloaddir", default=None, dest="downloaddir", help="directory to download corpus files to")
    optparser.add_option("--intermediateFiles", default=False, action="store_true", dest="intermediateFiles", help="save intermediate corpus files")
    optparser.add_option("--redownload", default=False, action="store_true", dest="redownload", help="re-download all source files")
    optparser.add_option("--debug", default=False, action="store_true", dest="debug", help="Keep temporary files")
    (options, args) = optparser.parse_args()

    convertDDI(options.outdir, options.downloaddir, options.redownload, options.intermediateFiles, options.debug)


text:
from django.core.management.base import BaseCommand, CommandError
import gspread
from main.models import Location, Organization

def to_bool(v):
    if str(v).lower() == 'y':
        return True
    return False

class Command(BaseCommand):
    args = 'Usage: load_locations <google_user> <google_pass>'
    help = 'Load locations from google spreadsheet'

    def handle(self, *args, **options):
        if len(args) != 2:
            print self.args
            return
        org = Organization.objects.all()[0]
        key = '0AgUErk7rE6TLdGJ0NE90U2pDVE9MRkZrU2hGR0FhRlE'
        key = '1dxJ-xw5K8k0q3YBmEuD5rIkdxG8eoV8eM3NPNFhk9QQ'
        gc = gspread.login(args[0], args[1])
        sht = gc.open_by_key(key).get_worksheet(0)
        values = sht.get_all_values()
        for v in values[1:]:
            [name, type, lat, long, ped, w, e, n, s, street1, street2] = v[:11]
            print "%s %s %s %s" % (name, type, lat, long)
            # This will create if not found
            #loc, c = Location.objects.get_or_create(organization=org, name=name)
            # Only update
            loc = Location.objects.get(organization=org, name=name)
            loc.type = type
            loc.latitude = lat
            loc.longitude = long
            loc.has_east = to_bool(e)
            loc.has_west = to_bool(w)
            loc.has_north = to_bool(n)
            loc.has_south = to_bool(s)
            loc.direction1 = street1
            loc.direction2 = street2
            loc.save()


text:
package com.bdc.ociney.modele;

import com.google.gson.annotations.Expose;

public class Version {

    @Expose
    private String original;
    @Expose
    private Integer code;
    @Expose
    private Integer lang;
    @Expose
    private String $;

    public String getOriginal() {
        return original;
    }

    public void setOriginal(String original) {
        this.original = original;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public Integer getLang() {
        return lang;
    }

    public void setLang(Integer lang) {
        this.lang = lang;
    }

    public String get$() {
        return $;
    }

    public void set$(String $) {
        this.$ = $;
    }

    @Override
    public String toString() {
        return "Version{" +
                "original='" + original + '\'' +
                ", code=" + code +
                ", lang=" + lang +
                ", $='" + $ + '\'' +
                '}';
    }
}


text:
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/download/internal/background_service/stats.h"

#include <map>

#include "base/files/file_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "components/download/internal/background_service/startup_status.h"
#include "components/download/public/background_service/clients.h"

namespace download {
namespace stats {
namespace {

// The maximum tracked file size in KB, larger files will fall into overflow
// bucket.
const int64_t kMaxFileSizeKB = 4 * 1024 * 1024; /* 4GB */

// Enum used by UMA metrics to track various reasons of pausing a download.
enum class PauseReason {
  // The download was paused. The reason can be anything.
  ANY = 0,

  // The download was paused due to unsatisfied device criteria.
  UNMET_DEVICE_CRITERIA = 1,

  // The download was paused by client.
  PAUSE_BY_CLIENT = 2,

  // The download was paused due to external download.
  EXTERNAL_DOWNLOAD = 3,

  // The download was paused due to navigation.
  EXTERNAL_NAVIGATION = 4,

  // The count of entries for the enum.
  COUNT = 5,
};

// Converts DownloadTaskType to histogram suffix.
// Should maps to suffix string in histograms.xml.
std::string TaskTypeToHistogramSuffix(DownloadTaskType task_type) {
  switch (task_type) {
    case DownloadTaskType::DOWNLOAD_TASK:
      return "DownloadTask";
    case DownloadTaskType::CLEANUP_TASK:
      return "CleanUpTask";
    case DownloadTaskType::DOWNLOAD_AUTO_RESUMPTION_TASK:
      NOTREACHED();
      return "DownloadAutoResumptionTask";
    case DownloadTaskType::DOWNLOAD_LATER_TASK:
      NOTREACHED();
      return "DownloadLaterTask";
  }
  NOTREACHED();
  return std::string();
}

// Converts FileCleanupReason to histogram suffix.
// Should maps to suffix string in histograms.xml.
std::string FileCleanupReasonToHistogramSuffix(FileCleanupReason reason) {
  switch (reason) {
    case FileCleanupReason::TIMEOUT:
      return "Timeout";
    case FileCleanupReason::ORPHANED:
      return "Orphaned";
    case FileCleanupReason::UNKNOWN:
      return "Unknown";
    case FileCleanupReason::HARD_RECOVERY:
      return "HardRecovery";
    case FileCleanupReason::COUNT:
      NOTREACHED();
  }
  NOTREACHED();
  return std::string();
}

// Helper method to log the pause reason for a particular download.
void LogDownloadPauseReason(PauseReason reason, bool on_upload_data_received) {
  std::string name(on_upload_data_received
                       ? "Download.Service.OnUploadDataReceived.PauseReason"
                       : "Download.Service.PauseReason");

  base::UmaHistogramEnumeration(name, reason, PauseReason::COUNT);
}

}  // namespace

void LogControllerStartupStatus(bool in_recovery, const StartupStatus& status) {
  DCHECK(status.Complete());

  // Total counts for general success/failure rate.
  LogStartUpResult(in_recovery, status.Ok() ? StartUpResult::SUCCESS
                                            : StartUpResult::FAILURE);

  // Failure reasons.
  if (!status.driver_ok.value())
    LogStartUpResult(in_recovery, StartUpResult::FAILURE_REASON_DRIVER);
  if (!status.model_ok.value())
    LogStartUpResult(in_recovery, StartUpResult::FAILURE_REASON_MODEL);
  if (!status.file_monitor_ok.value())
    LogStartUpResult(in_recovery, StartUpResult::FAILURE_REASON_FILE_MONITOR);
}

void LogStartUpResult(bool in_recovery, StartUpResult result) {
  if (in_recovery) {
    base::UmaHistogramEnumeration("Download.Service.StartUpStatus.Recovery",
                                  result, StartUpResult::COUNT);
  } else {
    base::UmaHistogramEnumeration(
        "Download.Service.StartUpStatus.Initialization", result,
        StartUpResult::COUNT);
  }
}

void LogServiceApiAction(DownloadClient client, ServiceApiAction action) {
  // Total count for each action.
  std::string name("Download.Service.Request.ClientAction");
  base::UmaHistogramEnumeration(name, action, ServiceApiAction::COUNT);

  // Total count for each action with client suffix.
  name.append(".").append(BackgroundDownloadClientToString(client));
  base::UmaHistogramEnumeration(name, action, ServiceApiAction::COUNT);
}

void LogStartDownloadResult(DownloadClient client,
                            DownloadParams::StartResult result) {
  // Total count for each start result.
  std::string name("Download.Service.Request.StartResult");
  base::UmaHistogramEnumeration(name, result,
                                DownloadParams::StartResult::COUNT);

  // Total count for each client result with client suffix.
  name.append(".").append(BackgroundDownloadClientToString(client));
  base::UmaHistogramEnumeration(name, result,
                                DownloadParams::StartResult::COUNT);
}

void LogDownloadCompletion(DownloadClient client,
                           CompletionType type,
                           uint64_t file_size_bytes) {
  // Records completion type.
  UMA_HISTOGRAM_ENUMERATION("Download.Service.Finish.Type", type,
                            CompletionType::COUNT);

  // Records the file size.
  std::string name("Download.Service.Complete.FileSize.");
  name.append(BackgroundDownloadClientToString(client));
  uint64_t file_size_kb = file_size_bytes / 1024;
  base::UmaHistogramCustomCounts(name, static_cast<int>(file_size_kb), 1,
                                 kMaxFileSizeKB, 50);
}

void LogDownloadPauseReason(const DownloadBlockageStatus& blockage_status,
                            bool currently_in_progress) {
  LogDownloadPauseReason(PauseReason::ANY, currently_in_progress);

  if (blockage_status.blocked_by_criteria)
    LogDownloadPauseReason(PauseReason::UNMET_DEVICE_CRITERIA,
                           currently_in_progress);

  if (blockage_status.entry_not_active)
    LogDownloadPauseReason(PauseReason::PAUSE_BY_CLIENT, currently_in_progress);

  if (blockage_status.blocked_by_navigation)
    LogDownloadPauseReason(PauseReason::EXTERNAL_NAVIGATION,
                           currently_in_progress);

  if (blockage_status.blocked_by_downloads)
    LogDownloadPauseReason(PauseReason::EXTERNAL_DOWNLOAD,
                           currently_in_progress);
}

void LogScheduledTaskStatus(DownloadTaskType task_type,
                            ScheduledTaskStatus status) {
  std::string name("Download.Service.TaskScheduler.Status");
  base::UmaHistogramEnumeration(name, status, ScheduledTaskStatus::COUNT);

  name.append(".").append(TaskTypeToHistogramSuffix(task_type));
  base::UmaHistogramEnumeration(name, status, ScheduledTaskStatus::COUNT);
}

void LogsFileDirectoryCreationError(base::File::Error error) {
  // Maps to histogram enum PlatformFileError.
  UMA_HISTOGRAM_ENUMERATION("Download.Service.Files.DirCreationError", -error,
                            -base::File::Error::FILE_ERROR_MAX);
}

void LogFileCleanupStatus(FileCleanupReason reason,
                          int succeeded_cleanups,
                          int failed_cleanups,
                          int external_cleanups) {
  std::string name("Download.Service.Files.CleanUp.Success");
  base::UmaHistogramCounts100(name, succeeded_cleanups);
  name.append(".").append(FileCleanupReasonToHistogramSuffix(reason));
  base::UmaHistogramCounts100(name, succeeded_cleanups);

  name = "Download.Service.Files.CleanUp.Failure";
  base::UmaHistogramCounts100(name, failed_cleanups);
  name.append(".").append(FileCleanupReasonToHistogramSuffix(reason));
  base::UmaHistogramCounts100(name, failed_cleanups);

  name = "Download.Service.Files.CleanUp.External";
  base::UmaHistogramCounts100(name, external_cleanups);
  name.append(".").append(FileCleanupReasonToHistogramSuffix(reason));
  base::UmaHistogramCounts100(name, external_cleanups);
}

void LogFileLifeTime(const base::TimeDelta& file_life_time) {
  UMA_HISTOGRAM_CUSTOM_TIMES("Download.Service.Files.LifeTime", file_life_time,
                             base::Seconds(1), base::Days(8), 100);
}

void LogEntryEvent(DownloadEvent event) {
  UMA_HISTOGRAM_ENUMERATION("Download.Service.Entry.Event", event,
                            DownloadEvent::COUNT);
}

void LogEntryRetryCount(uint32_t retry_count) {
  UMA_HISTOGRAM_COUNTS_100("Download.Service.Entry.RetryCount", retry_count);
}

void LogEntryRemovedWhileWaitingForUploadResponse() {
  UMA_HISTOGRAM_BOOLEAN("Download.Service.Upload.EntryNotFound", true);
}

void LogHasUploadData(DownloadClient client, bool has_upload_data) {
  std::string name("Download.Service.Upload.HasUploadData");
  name.append(".").append(BackgroundDownloadClientToString(client));
  base::UmaHistogramBoolean(name, has_upload_data);
}

}  // namespace stats
}  // namespace download


text:
class Entry < ActiveRecord::Base
  belongs_to :user
  belongs_to :topic
  has_many :tag_maps
  has_many :tags, through: :tag_maps

  scope :publicly_viewable, -> { where(public: true) }
  scope :privately_viewable, -> { where(public: false) }
  scope :visible_to, -> (user) { user ? all : publicly_viewable }

  mount_uploader :image, ImageUploader

  def self.tagged_with(name)
    Tag.find_by_name!(name).entries
  end

  def self.tag_counts
    Tag.select("tags.id, tags.name,count(tag_maps.tag_id) as count").
    joins(:tag_maps).group("tag_maps.tag_id, tags.id, tags.name")
  end

  def tag_list
    tags.map(&:name).join(", ")
  end

  def tag_list=(names)
    self.tags = names.split(",").map do |n|
      Tag.where(name: n.strip).first_or_create!
    end
  end
end


text:
default['virtuoso']['install_dir'] = '/usr/local/virtuoso'
default['virtuoso']['code_user']='root'
default['virtuoso']['code_group']='root'
default['virtuoso']['code_dir']='/usr/local/src/virtuoso'
default['virtuoso']['revision']='stable/7'
default['virtuoso']['cflags']='-O2 -m64'


text:
#ifndef API_TEST_PEERCONNECTION_QUALITY_TEST_FIXTURE_H_
#define API_TEST_PEERCONNECTION_QUALITY_TEST_FIXTURE_H_

#include <map>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "absl/memory/memory.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "api/async_resolver_factory.h"
#include "api/call/call_factory_interface.h"
#include "api/fec_controller.h"
#include "api/function_view.h"
#include "api/media_stream_interface.h"
#include "api/peer_connection_interface.h"
#include "api/rtc_event_log/rtc_event_log_factory_interface.h"
#include "api/rtp_parameters.h"
#include "api/task_queue/task_queue_factory.h"
#include "api/test/audio_quality_analyzer_interface.h"
#include "api/test/frame_generator_interface.h"
#include "api/test/simulated_network.h"
#include "api/test/stats_observer_interface.h"
#include "api/test/video_quality_analyzer_interface.h"
#include "api/transport/media/media_transport_interface.h"
#include "api/transport/network_control.h"
#include "api/units/time_delta.h"
#include "api/video_codecs/video_decoder_factory.h"
#include "api/video_codecs/video_encoder.h"
#include "api/video_codecs/video_encoder_factory.h"
#include "media/base/media_constants.h"
#include "rtc_base/network.h"
#include "rtc_base/rtc_certificate_generator.h"
#include "rtc_base/ssl_certificate.h"
#include "rtc_base/thread.h"

namespace webrtc {
namespace webrtc_pc_e2e {

constexpr size_t kDefaultSlidesWidth = 1850;
constexpr size_t kDefaultSlidesHeight = 1110;

// API is in development. Can be changed/removed without notice.
class PeerConnectionE2EQualityTestFixture {
 public:
  // The index of required capturing device in OS provided list of video
  // devices. On Linux and Windows the list will be obtained via
  // webrtc::VideoCaptureModule::DeviceInfo, on Mac OS via
  // [RTCCameraVideoCapturer captureDevices].
  enum class CapturingDeviceIndex : size_t {};

  // Contains parameters for screen share scrolling.
  //
  // If scrolling is enabled, then it will be done by putting sliding window
  // on source video and moving this window from top left corner to the
  // bottom right corner of the picture.
  //
  // In such case source dimensions must be greater or equal to the sliding
  // window dimensions. So |source_width| and |source_height| are the dimensions
  // of the source frame, while |VideoConfig::width| and |VideoConfig::height|
  // are the dimensions of the sliding window.
  //
  // Because |source_width| and |source_height| are dimensions of the source
  // frame, they have to be width and height of videos from
  // |ScreenShareConfig::slides_yuv_file_names|.
  //
  // Because scrolling have to be done on single slide it also requires, that
  // |duration| must be less or equal to
  // |ScreenShareConfig::slide_change_interval|.
  struct ScrollingParams {
    ScrollingParams(TimeDelta duration,
                    size_t source_width,
                    size_t source_height)
        : duration(duration),
          source_width(source_width),
          source_height(source_height) {
      RTC_CHECK_GT(duration.ms(), 0);
    }

    // Duration of scrolling.
    TimeDelta duration;
    // Width of source slides video.
    size_t source_width;
    // Height of source slides video.
    size_t source_height;
  };

  // Contains screen share video stream properties.
  struct ScreenShareConfig {
    explicit ScreenShareConfig(TimeDelta slide_change_interval)
        : slide_change_interval(slide_change_interval) {
      RTC_CHECK_GT(slide_change_interval.ms(), 0);
    }

    // Shows how long one slide should be presented on the screen during
    // slide generation.
    TimeDelta slide_change_interval;
    // If true, slides will be generated programmatically. No scrolling params
    // will be applied in such case.
    bool generate_slides = false;
    // If present scrolling will be applied. Please read extra requirement on
    // |slides_yuv_file_names| for scrolling.
    absl::optional<ScrollingParams> scrolling_params;
    // Contains list of yuv files with slides.
    //
    // If empty, default set of slides will be used. In such case
    // |VideoConfig::width| must be equal to |kDefaultSlidesWidth| and
    // |VideoConfig::height| must be equal to |kDefaultSlidesHeight| or if
    // |scrolling_params| are specified, then |ScrollingParams::source_width|
    // must be equal to |kDefaultSlidesWidth| and
    // |ScrollingParams::source_height| must be equal to |kDefaultSlidesHeight|.
    std::vector<std::string> slides_yuv_file_names;
  };

  // Config for Vp8 simulcast or Vp9 SVC testing.
  //
  // SVC support is limited:
  // During SVC testing there is no SFU, so framework will try to emulate SFU
  // behavior in regular p2p call. Because of it there are such limitations:
  //  * if |target_spatial_index| is not equal to the highest spatial layer
  //    then no packet/frame drops are allowed.
  //
  //    If there will be any drops, that will affect requested layer, then
  //    WebRTC SVC implementation will continue decoding only the highest
  //    available layer and won't restore lower layers, so analyzer won't
  //    receive required data which will cause wrong results or test failures.
  struct VideoSimulcastConfig {
    explicit VideoSimulcastConfig(int simulcast_streams_count)
        : simulcast_streams_count(simulcast_streams_count) {
      RTC_CHECK_GT(simulcast_streams_count, 1);
    }
    VideoSimulcastConfig(int simulcast_streams_count, int target_spatial_index)
        : simulcast_streams_count(simulcast_streams_count),
          target_spatial_index(target_spatial_index) {
      RTC_CHECK_GT(simulcast_streams_count, 1);
      RTC_CHECK_GE(target_spatial_index, 0);
      RTC_CHECK_LT(target_spatial_index, simulcast_streams_count);
    }

    // Specified amount of simulcast streams/SVC layers, depending on which
    // encoder is used.
    int simulcast_streams_count;
    // Specifies spatial index of the video stream to analyze.
    // There are 2 cases:
    // 1. simulcast encoder is used:
    //    in such case |target_spatial_index| will specify the index of
    //    simulcast stream, that should be analyzed. Other streams will be
    //    dropped.
    // 2. SVC encoder is used:
    //    in such case |target_spatial_index| will specify the top interesting
    //    spatial layer and all layers below, including target one will be
    //    processed. All layers above target one will be dropped.
    // If not specified than whatever stream will be received will be analyzed.
    // It requires Selective Forwarding Unit (SFU) to be configured in the
    // network.
    absl::optional<int> target_spatial_index;

    // Encoding parameters per simulcast layer. If not empty, |encoding_params|
    // size have to be equal to |simulcast_streams_count|. Will be used to set
    // transceiver send encoding params for simulcast layers. Applicable only
    // for codecs that support simulcast (ex. Vp8) and will be ignored
    // otherwise. RtpEncodingParameters::rid may be changed by fixture
    // implementation to ensure signaling correctness.
    std::vector<RtpEncodingParameters> encoding_params;
  };

  // Contains properties of single video stream.
  struct VideoConfig {
    VideoConfig(size_t width, size_t height, int32_t fps)
        : width(width), height(height), fps(fps) {}

    // Video stream width.
    const size_t width;
    // Video stream height.
    const size_t height;
    const int32_t fps;
    // Have to be unique among all specified configs for all peers in the call.
    // Will be auto generated if omitted.
    absl::optional<std::string> stream_label;
    // Will be set for current video track. If equals to kText or kDetailed -
    // screencast in on.
    absl::optional<VideoTrackInterface::ContentHint> content_hint;
    // If presented video will be transfered in simulcast/SVC mode depending on
    // which encoder is used.
    //
    // Simulcast is supported only from 1st added peer. For VP8 simulcast only
    // without RTX is supported so it will be automatically disabled for all
    // simulcast tracks. For VP9 simulcast enables VP9 SVC mode and support RTX,
    // but only on non-lossy networks. See more in documentation to
    // VideoSimulcastConfig.
    absl::optional<VideoSimulcastConfig> simulcast_config;
    // Count of temporal layers for video stream. This value will be set into
    // each RtpEncodingParameters of RtpParameters of corresponding
    // RtpSenderInterface for this video stream.
    absl::optional<int> temporal_layers_count;
    // Sets the maximum encode bitrate in bps. If this value is not set, the
    // encoder will be capped at an internal maximum value around 2 Mbps
    // depending on the resolution. This means that it will never be able to
    // utilize a high bandwidth link.
    absl::optional<int> max_encode_bitrate_bps;
    // Sets the minimum encode bitrate in bps. If this value is not set, the
    // encoder will use an internal minimum value. Please note that if this
    // value is set higher than the bandwidth of the link, the encoder will
    // generate more data than the link can handle regardless of the bandwidth
    // estimation.
    absl::optional<int> min_encode_bitrate_bps;
    // If specified the input stream will be also copied to specified file.
    // It is actually one of the test's output file, which contains copy of what
    // was captured during the test for this video stream on sender side.
    // It is useful when generator is used as input.
    absl::optional<std::string> input_dump_file_name;
    // If specified this file will be used as output on the receiver side for
    // this stream. If multiple streams will be produced by input stream,
    // output files will be appended with indexes. The produced files contains
    // what was rendered for this video stream on receiver side.
    absl::optional<std::string> output_dump_file_name;
    // If true will display input and output video on the user's screen.
    bool show_on_screen = false;
    // If specified, determines a sync group to which this video stream belongs.
    // According to bugs.webrtc.org/4762 WebRTC supports synchronization only
    // for pair of single audio and single video stream. Framework won't do any
    // enforcements on this field.
    absl::optional<std::string> sync_group;
  };

  // Contains properties for audio in the call.
  struct AudioConfig {
    enum Mode {
      kGenerated,
      kFile,
    };
    // Have to be unique among all specified configs for all peers in the call.
    // Will be auto generated if omitted.
    absl::optional<std::string> stream_label;
    Mode mode = kGenerated;
    // Have to be specified only if mode = kFile
    absl::optional<std::string> input_file_name;
    // If specified the input stream will be also copied to specified file.
    absl::optional<std::string> input_dump_file_name;
    // If specified the output stream will be copied to specified file.
    absl::optional<std::string> output_dump_file_name;

    // Audio options to use.
    cricket::AudioOptions audio_options;
    // Sampling frequency of input audio data (from file or generated).
    int sampling_frequency_in_hz = 48000;
    // If specified, determines a sync group to which this audio stream belongs.
    // According to bugs.webrtc.org/4762 WebRTC supports synchronization only
    // for pair of single audio and single video stream. Framework won't do any
    // enforcements on this field.
    absl::optional<std::string> sync_group;
  };

  // This class is used to fully configure one peer inside the call.
  class PeerConfigurer {
   public:
    virtual ~PeerConfigurer() = default;

    // Sets peer name that will be used to report metrics related to this peer.
    // If not set, some default name will be assigned. All names have to be
    // unique.
    virtual PeerConfigurer* SetName(absl::string_view name) = 0;

    // The parameters of the following 9 methods will be passed to the
    // PeerConnectionFactoryInterface implementation that will be created for
    // this peer.
    virtual PeerConfigurer* SetTaskQueueFactory(
        std::unique_ptr<TaskQueueFactory> task_queue_factory) = 0;
    virtual PeerConfigurer* SetCallFactory(
        std::unique_ptr<CallFactoryInterface> call_factory) = 0;
    virtual PeerConfigurer* SetEventLogFactory(
        std::unique_ptr<RtcEventLogFactoryInterface> event_log_factory) = 0;
    virtual PeerConfigurer* SetFecControllerFactory(
        std::unique_ptr<FecControllerFactoryInterface>
            fec_controller_factory) = 0;
    virtual PeerConfigurer* SetNetworkControllerFactory(
        std::unique_ptr<NetworkControllerFactoryInterface>
            network_controller_factory) = 0;
    virtual PeerConfigurer* SetMediaTransportFactory(
        std::unique_ptr<MediaTransportFactory> media_transport_factory) = 0;
    virtual PeerConfigurer* SetVideoEncoderFactory(
        std::unique_ptr<VideoEncoderFactory> video_encoder_factory) = 0;
    virtual PeerConfigurer* SetVideoDecoderFactory(
        std::unique_ptr<VideoDecoderFactory> video_decoder_factory) = 0;
    // Set a custom NetEqFactory to be used in the call.
    virtual PeerConfigurer* SetNetEqFactory(
        std::unique_ptr<NetEqFactory> neteq_factory) = 0;

    // The parameters of the following 4 methods will be passed to the
    // PeerConnectionInterface implementation that will be created for this
    // peer.
    virtual PeerConfigurer* SetAsyncResolverFactory(
        std::unique_ptr<webrtc::AsyncResolverFactory>
            async_resolver_factory) = 0;
    virtual PeerConfigurer* SetRTCCertificateGenerator(
        std::unique_ptr<rtc::RTCCertificateGeneratorInterface>
            cert_generator) = 0;
    virtual PeerConfigurer* SetSSLCertificateVerifier(
        std::unique_ptr<rtc::SSLCertificateVerifier> tls_cert_verifier) = 0;
    virtual PeerConfigurer* SetIceTransportFactory(
        std::unique_ptr<IceTransportFactory> factory) = 0;

    // Add new video stream to the call that will be sent from this peer.
    // Default implementation of video frames generator will be used.
    virtual PeerConfigurer* AddVideoConfig(VideoConfig config) = 0;
    // Add new video stream to the call that will be sent from this peer with
    // provided own implementation of video frames generator.
    virtual PeerConfigurer* AddVideoConfig(
        VideoConfig config,
        std::unique_ptr<test::FrameGeneratorInterface> generator) = 0;
    // Add new video stream to the call that will be sent from this peer.
    // Capturing device with specified index will be used to get input video.
    virtual PeerConfigurer* AddVideoConfig(
        VideoConfig config,
        CapturingDeviceIndex capturing_device_index) = 0;
    // Set the audio stream for the call from this peer. If this method won't
    // be invoked, this peer will send no audio.
    virtual PeerConfigurer* SetAudioConfig(AudioConfig config) = 0;
    // If is set, an RTCEventLog will be saved in that location and it will be
    // available for further analysis.
    virtual PeerConfigurer* SetRtcEventLogPath(std::string path) = 0;
    // If is set, an AEC dump will be saved in that location and it will be
    // available for further analysis.
    virtual PeerConfigurer* SetAecDumpPath(std::string path) = 0;
    virtual PeerConfigurer* SetRTCConfiguration(
        PeerConnectionInterface::RTCConfiguration configuration) = 0;
    // Set bitrate parameters on PeerConnection. This constraints will be
    // applied to all summed RTP streams for this peer.
    virtual PeerConfigurer* SetBitrateParameters(
        PeerConnectionInterface::BitrateParameters bitrate_params) = 0;
  };

  // Contains configuration for echo emulator.
  struct EchoEmulationConfig {
    // Delay which represents the echo path delay, i.e. how soon rendered signal
    // should reach capturer.
    TimeDelta echo_delay = TimeDelta::Millis(50);
  };

  struct VideoCodecConfig {
    explicit VideoCodecConfig(std::string name)
        : name(std::move(name)), required_params() {}
    VideoCodecConfig(std::string name,
                     std::map<std::string, std::string> required_params)
        : name(std::move(name)), required_params(std::move(required_params)) {}
    // Next two fields are used to specify concrete video codec, that should be
    // used in the test. Video code will be negotiated in SDP during offer/
    // answer exchange.
    // Video codec name. You can find valid names in
    // media/base/media_constants.h
    std::string name = cricket::kVp8CodecName;
    // Map of parameters, that have to be specified on SDP codec. Each parameter
    // is described by key and value. Codec parameters will match the specified
    // map if and only if for each key from |required_params| there will be
    // a parameter with name equal to this key and parameter value will be equal
    // to the value from |required_params| for this key.
    // If empty then only name will be used to match the codec.
    std::map<std::string, std::string> required_params;
  };

  // Contains parameters, that describe how long framework should run quality
  // test.
  struct RunParams {
    explicit RunParams(TimeDelta run_duration) : run_duration(run_duration) {}

    // Specifies how long the test should be run. This time shows how long
    // the media should flow after connection was established and before
    // it will be shut downed.
    TimeDelta run_duration;

    // List of video codecs to use during the test. These codecs will be
    // negotiated in SDP during offer/answer exchange. The order of these codecs
    // during negotiation will be the same as in |video_codecs|. Codecs have
    // to be available in codecs list provided by peer connection to be
    // negotiated. If some of specified codecs won't be found, the test will
    // crash.
    // If list is empty Vp8 with no required_params will be used.
    std::vector<VideoCodecConfig> video_codecs;
    bool use_ulp_fec = false;
    bool use_flex_fec = false;
    // Specifies how much video encoder target bitrate should be different than
    // target bitrate, provided by WebRTC stack. Must be greater then 0. Can be
    // used to emulate overshooting of video encoders. This multiplier will
    // be applied for all video encoder on both sides for all layers. Bitrate
    // estimated by WebRTC stack will be multiplied on this multiplier and then
    // provided into VideoEncoder::SetRates(...).
    double video_encoder_bitrate_multiplier = 1.0;
    // If true will set conference mode in SDP media section for all video
    // tracks for all peers.
    bool use_conference_mode = false;
    // If specified echo emulation will be done, by mixing the render audio into
    // the capture signal. In such case input signal will be reduced by half to
    // avoid saturation or compression in the echo path simulation.
    absl::optional<EchoEmulationConfig> echo_emulation_config;
  };

  // Represent an entity that will report quality metrics after test.
  class QualityMetricsReporter : public StatsObserverInterface {
   public:
    virtual ~QualityMetricsReporter() = default;

    // Invoked by framework after peer connection factory and peer connection
    // itself will be created but before offer/answer exchange will be started.
    virtual void Start(absl::string_view test_case_name) = 0;

    // Invoked by framework after call is ended and peer connection factory and
    // peer connection are destroyed.
    virtual void StopAndReportResults() = 0;
  };

  virtual ~PeerConnectionE2EQualityTestFixture() = default;

  // Add activity that will be executed on the best effort at least after
  // |target_time_since_start| after call will be set up (after offer/answer
  // exchange, ICE gathering will be done and ICE candidates will passed to
  // remote side). |func| param is amount of time spent from the call set up.
  virtual void ExecuteAt(TimeDelta target_time_since_start,
                         std::function<void(TimeDelta)> func) = 0;
  // Add activity that will be executed every |interval| with first execution
  // on the best effort at least after |initial_delay_since_start| after call
  // will be set up (after all participants will be connected). |func| param is
  // amount of time spent from the call set up.
  virtual void ExecuteEvery(TimeDelta initial_delay_since_start,
                            TimeDelta interval,
                            std::function<void(TimeDelta)> func) = 0;

  // Add stats reporter entity to observe the test.
  virtual void AddQualityMetricsReporter(
      std::unique_ptr<QualityMetricsReporter> quality_metrics_reporter) = 0;

  // Add a new peer to the call and return an object through which caller
  // can configure peer's behavior.
  // |network_thread| will be used as network thread for peer's peer connection
  // |network_manager| will be used to provide network interfaces for peer's
  // peer connection.
  // |configurer| function will be used to configure peer in the call.
  virtual void AddPeer(rtc::Thread* network_thread,
                       rtc::NetworkManager* network_manager,
                       rtc::FunctionView<void(PeerConfigurer*)> configurer) = 0;
  virtual void Run(RunParams run_params) = 0;

  // Returns real test duration - the time of test execution measured during
  // test. Client must call this method only after test is finished (after
  // Run(...) method returned). Test execution time is time from end of call
  // setup (offer/answer, ICE candidates exchange done and ICE connected) to
  // start of call tear down (PeerConnection closed).
  virtual TimeDelta GetRealTestDuration() const = 0;
};

}  // namespace webrtc_pc_e2e
}  // namespace webrtc

#endif  // API_TEST_PEERCONNECTION_QUALITY_TEST_FIXTURE_H_


text:
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  #add_breadcrumb :index, :root_path
  protect_from_forgery with: :exception
end


text:
require "spec_helper"

describe Kwipper::Response do
  subject { described_class.new Fixtures.request }
  let(:session_cookie_name) { described_class::SESSION_COOKIE_NAME }
  let(:session_cookie_value) { subject.session_cookie_value }
  let :response_with_session do
    described_class.new Fixtures.request cookies: { session_cookie_name => "something" }
  end

  context "#info" do
    it "returns a string of the HTTP status code and message" do
      expect(subject.info).to eq "200 OK"
    end
  end

  context "#headers" do
    it "returns a hash and memoizes it" do
      expect(subject.headers).to be_a Hash
      expect(subject.headers.object_id).to be subject.headers.object_id
    end

    it "sets the session cookie if it doesn't exist in the request" do
      cookie = subject.headers["Set-Cookie"]
      expect(cookie).to match session_cookie_name
    end

    it "doesn't change the session cookie if there's one in the request" do
      expect(response_with_session.headers['Set-Cookie']).to be nil
    end
  end

  context "#set_status" do
    it "takes a symbol and sets the HTTP status code and message" do
      subject.set_status :found

      expect(subject.status_code).to be 302
      expect(subject.status_message).to eq "Found"
    end
  end

  context "#current_user" do
    let(:user) { Fixtures.user }
    let(:session) { Fixtures.session id: session_cookie_value, user_id: user.id }

    it "returns a user instance when there's a user_id in the session" do
      subject.request.cookies[session_cookie_name] = session.session_id

      expect(subject.current_user.id).to be user.id
    end

    it "returns nil if there's no session" do
      expect(subject.current_user).to be nil
    end
  end

  context "#current_session" do
    let(:session) { Fixtures.session id: session_cookie_value }

    it "returns a session instance when there's a session cookie in the request" do
      subject.request.cookies[session_cookie_name] = session.session_id

      expect(subject.current_session.session_id).to eq session.session_id
    end

    it "returns nil when theres no session cookie in the request" do
      expect(subject.current_session).to be nil
    end
  end

  context "#to_http_response" do
    it "outputs the HTTP response string with headers and a nice body" do
      subject.redirect = "/test"
      subject.set_status :found
      subject.body = "Nice"

      expect(subject.to_http_response).to eq <<-HTTP
HTTP/1.1 302 Found
Set-Cookie: kwipper_session=#{subject.session_cookie_value}; HttpOnly\r
Content-Length: 4\r
Content-Type: text/html\r
Location: /test

Nice
      HTTP
    end
  end

  context "#session_cookie_value" do
    it "gets the session cookie from the request" do
      subject.request.cookies[session_cookie_name] = "set via request cookie"

      expect(subject.session_cookie_value).to eq "set via request cookie"
    end

    it "generates a random session cookie if there's none in the request" do
      expect(subject.session_cookie_value).to eq subject.instance_variable_get :@generated_cookie_value
    end
  end

  context "#remove_session_cookie" do
    it "sets a session cookie destroyer in the response headers" do
      subject.remove_session_cookie

      expect(subject.headers["Set-Cookie"]).to match "x; expires"
    end
  end
end


text:
typedef struct shape{
    struct pri *attr;
    struct pub *fun;
} shape;

typedef struct pri{
    char type[10];
    double length;
} pri;

typedef struct pub{
    double (*area)(double length);
} pub;
//获取面积的公共方法,传入不同的对象获取面积
double shape_area(shape *shape);
#endif


text:
function recompute() {
    var sum = 0;
    $.each($('#budgetPlanForm').serializeArray(), function (i, field) {
        if (field.name.indexOf("ExpectedValue") >= 0) {
            sum += parseFloat(field.value);
        }
    });

    var incomes = parseFloat($('#ExpectedIncomes').val());
    var savings = parseFloat($('#ExpectedSavings').val());
    var total = incomes - sum - savings;
    $('#TotalExpectedValue').attr("value", sum.toFixed(2));
    $('#Total').attr("value", total.toFixed(2));
    if (total > 200) {
        $('#Total').css("background-color", "rgba(55, 152, 55, 0.5)");
    }
    else {
        $('#Total').css("background-color", "rgba(255,0,0,0.5)");
    }
}

function createBudgetPlan() {

    $.post('Create/', $('#budgetPlanForm').serialize())
        .done(function (data) {
            if (data.Result) {
                window.location = data.RedirectLocation;
            }
            else {
                handleJsonValidationErrors(data.ErrorMessages);
            }
        });
}

function editBudgetPlan() {

    var id = parseInt($("#Id").val());

    $.post(id, $('#budgetPlanForm').serialize())
        .done(function (data) {
            if (data.Result) {
                window.location = data.RedirectLocation;
            }
            else {
                handleJsonValidationErrors(data.ErrorMessages);
            }
        });
}


text:
import { GraphQLSchema, GraphQLOutputType, SelectionSetNode, FieldNode, GraphQLResolveInfo, GraphQLFieldResolver, FragmentDefinitionNode, GraphQLObjectType, VariableDefinitionNode, OperationTypeNode, GraphQLError } from 'graphql';
import DataLoader from 'dataloader';
import { ExecutionParams, ExecutionResult, Executor, Request, Subscriber, TypeMap } from '@graphql-tools/utils';
import { Subschema } from './Subschema';
import { OBJECT_SUBSCHEMA_SYMBOL, FIELD_SUBSCHEMA_MAP_SYMBOL, UNPATHED_ERRORS_SYMBOL } from './symbols';
export declare type SchemaTransform = (originalWrappingSchema: GraphQLSchema, subschemaConfig: SubschemaConfig, transformedSchema?: GraphQLSchema) => GraphQLSchema;
export declare type RequestTransform<T = Record<string, any>> = (originalRequest: Request, delegationContext: DelegationContext, transformationContext: T) => Request;
export declare type ResultTransform<T = Record<string, any>> = (originalResult: ExecutionResult, delegationContext: DelegationContext, transformationContext: T) => ExecutionResult;
export interface Transform<T = Record<string, any>> {
    transformSchema?: SchemaTransform;
    transformRequest?: RequestTransform<T>;
    transformResult?: ResultTransform<T>;
}
export interface DelegationContext {
    subschema: GraphQLSchema | SubschemaConfig;
    targetSchema: GraphQLSchema;
    operation: OperationTypeNode;
    fieldName: string;
    args: Record<string, any>;
    context: Record<string, any>;
    info: GraphQLResolveInfo;
    returnType: GraphQLOutputType;
    onLocatedError?: (originalError: GraphQLError) => GraphQLError;
    transforms: Array<Transform>;
    transformedSchema: GraphQLSchema;
    skipTypeMerging: boolean;
}
export declare type DelegationBinding = (delegationContext: DelegationContext) => Array<Transform>;
export interface IDelegateToSchemaOptions<TContext = Record<string, any>, TArgs = Record<string, any>> {
    schema: GraphQLSchema | SubschemaConfig<any, any, any, TContext>;
    operationName?: string;
    operation?: OperationTypeNode;
    fieldName?: string;
    returnType?: GraphQLOutputType;
    onLocatedError?: (originalError: GraphQLError) => GraphQLError;
    args?: TArgs;
    selectionSet?: SelectionSetNode;
    fieldNodes?: ReadonlyArray<FieldNode>;
    context?: TContext;
    info: GraphQLResolveInfo;
    rootValue?: Record<string, any>;
    transforms?: Array<Transform>;
    transformedSchema?: GraphQLSchema;
    skipValidation?: boolean;
    skipTypeMerging?: boolean;
    binding?: DelegationBinding;
}
export interface IDelegateRequestOptions<TContext = Record<string, any>, TArgs = Record<string, any>> extends Omit<IDelegateToSchemaOptions<TContext, TArgs>, 'info'> {
    request: Request;
    info?: GraphQLResolveInfo;
}
export interface ICreateRequestFromInfo {
    info: GraphQLResolveInfo;
    operationName?: string;
    operation: OperationTypeNode;
    fieldName: string;
    selectionSet?: SelectionSetNode;
    fieldNodes?: ReadonlyArray<FieldNode>;
}
export interface ICreateRequest {
    sourceSchema?: GraphQLSchema;
    sourceParentType?: GraphQLObjectType;
    sourceFieldName?: string;
    fragments?: Record<string, FragmentDefinitionNode>;
    variableDefinitions?: ReadonlyArray<VariableDefinitionNode>;
    variableValues?: Record<string, any>;
    targetOperation: OperationTypeNode;
    targetOperationName?: string;
    targetFieldName: string;
    selectionSet?: SelectionSetNode;
    fieldNodes?: ReadonlyArray<FieldNode>;
}
export interface MergedTypeInfo<TContext = Record<string, any>> {
    typeName: string;
    selectionSet?: SelectionSetNode;
    targetSubschemas: Map<Subschema, Array<Subschema>>;
    uniqueFields: Record<string, Subschema>;
    nonUniqueFields: Record<string, Array<Subschema>>;
    typeMaps: Map<GraphQLSchema | SubschemaConfig, TypeMap>;
    selectionSets: Map<Subschema, SelectionSetNode>;
    fieldSelectionSets: Map<Subschema, Record<string, SelectionSetNode>>;
    resolvers: Map<Subschema, MergedTypeResolver<TContext>>;
}
export interface ICreateProxyingResolverOptions<TContext = Record<string, any>> {
    subschemaConfig: SubschemaConfig<any, any, any, TContext>;
    transformedSchema?: GraphQLSchema;
    operation?: OperationTypeNode;
    fieldName?: string;
}
export declare type CreateProxyingResolverFn<TContext = Record<string, any>> = (options: ICreateProxyingResolverOptions<TContext>) => GraphQLFieldResolver<any, TContext>;
export interface BatchingOptions<K = any, V = any, C = K> {
    extensionsReducer?: (mergedExtensions: Record<string, any>, executionParams: ExecutionParams) => Record<string, any>;
    dataLoaderOptions?: DataLoader.Options<K, V, C>;
}
export interface SubschemaConfig<K = any, V = any, C = K, TContext = Record<string, any>> {
    schema: GraphQLSchema;
    createProxyingResolver?: CreateProxyingResolverFn<TContext>;
    transforms?: Array<Transform>;
    merge?: Record<string, MergedTypeConfig<any, any, TContext>>;
    rootValue?: Record<string, any>;
    executor?: Executor<TContext>;
    subscriber?: Subscriber<TContext>;
    batch?: boolean;
    batchingOptions?: BatchingOptions<K, V, C>;
}
export interface MergedTypeConfig<K = any, V = any, TContext = Record<string, any>> extends MergedTypeEntryPoint<K, V, TContext> {
    entryPoints?: Array<MergedTypeEntryPoint>;
    fields?: Record<string, MergedFieldConfig>;
    computedFields?: Record<string, {
        selectionSet?: string;
    }>;
    canonical?: boolean;
}
export interface MergedTypeEntryPoint<K = any, V = any, TContext = Record<string, any>> extends MergedTypeResolverOptions<K, V> {
    selectionSet?: string;
    key?: (originalResult: any) => K;
    resolve?: MergedTypeResolver<TContext>;
}
export interface MergedTypeResolverOptions<K = any, V = any> {
    fieldName?: string;
    args?: (originalResult: any) => Record<string, any>;
    argsFromKeys?: (keys: ReadonlyArray<K>) => Record<string, any>;
    valuesFromResults?: (results: any, keys: ReadonlyArray<K>) => Array<V>;
}
export interface MergedFieldConfig {
    selectionSet?: string;
    computed?: boolean;
    canonical?: boolean;
}
export declare type MergedTypeResolver<TContext = Record<string, any>> = (originalResult: any, context: TContext, info: GraphQLResolveInfo, subschema: GraphQLSchema | SubschemaConfig<any, any, any, TContext>, selectionSet: SelectionSetNode, key?: any) => any;
export interface StitchingInfo<TContext = Record<string, any>> {
    subschemaMap: Map<GraphQLSchema | SubschemaConfig<any, any, any, TContext>, Subschema<any, any, any, TContext>>;
    selectionSetsByType: Record<string, SelectionSetNode>;
    selectionSetsByField: Record<string, Record<string, SelectionSetNode>>;
    dynamicSelectionSetsByField: Record<string, Record<string, Array<(node: FieldNode) => SelectionSetNode>>>;
    mergedTypes: Record<string, MergedTypeInfo<TContext>>;
}
export interface ExternalObject<TContext = Record<string, any>> {
    key: any;
    [OBJECT_SUBSCHEMA_SYMBOL]: GraphQLSchema | SubschemaConfig<any, any, any, TContext>;
    [FIELD_SUBSCHEMA_MAP_SYMBOL]: Record<string, GraphQLSchema | SubschemaConfig<any, any, any, TContext>>;
    [UNPATHED_ERRORS_SYMBOL]: Array<GraphQLError>;
}


text:
const fs = require('fs');
const parse = require('csv-parse');
const stringify = require('csv-stringify');
const transform = require('stream-transform');
const PNG = require('node-png').PNG;

const BASE = 11;
const HORIZONTAL_TILES = 61;
const VERTICAL_TILES = 59;
const WIDTH = HORIZONTAL_TILES * BASE;
const HEIGHT = VERTICAL_TILES * BASE;
const SIZE = WIDTH * HEIGHT;
const MAX = 3925;

var input = fs.createReadStream('../workshop/long-cadence.csv');
var output = fs.createWriteStream('out.csv');
var parser = parse();
var stringifier = stringify();
var transformer = transform(function(data){
    return data;
});

var png = new PNG({
    width: WIDTH,
    height: HEIGHT,
    filter: -1
});

var row_index = 0;
transformer.on('readable', function(){
    var row;
    while (row = transformer.read()) {
        var data = row.slice(1);
        var offset_X = row_index % HORIZONTAL_TILES;
        var offset_Y = Math.floor(row_index/ HORIZONTAL_TILES);
        data.forEach(function(value, original_index){
            var offset_x = original_index % BASE;
            var offset_y = Math.floor(original_index / BASE);
            var target_index = offset_Y * (BASE * HORIZONTAL_TILES * BASE) +
                offset_X * BASE +
                offset_y * (HORIZONTAL_TILES * BASE) +
                offset_x;
            var gray = value/MAX * 255;
            png.data[4*target_index + 0] = gray;
            png.data[4*target_index + 1] = gray;
            png.data[4*target_index + 2] = gray;
            png.data[4*target_index + 3] = 0xff;
        });

        row_index++;
    }
});
transformer.on('finish', function(){
    png.pack().pipe(fs.createWriteStream('resources/collage.png'));
});

input
    .pipe(parser)
    .pipe(transformer)
    .pipe(stringifier)
    .pipe(output);


text:
import java.lang.annotation.*;
import java.util.List;

@Target({ElementType.TYPE_USE})
@interface TA { }

class Test {
  private void bar(@TA List<String> name) {
  }

}


text:
//
//  UIFont+NERChainable.h
//  NerdyUI
//
//  Created by nerdycat on 2016/12/14.
//  Copyright © 2016 nerdycat. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "NERUtils.h"

/**
 * Create a UIFont.
 * Fnt argument can be:
   1) UIFont object
   2) 15: systemFontOfSize 15
   3) @15: boldSystemFontOfSize 15
   4) @"headline", @"body", @"caption1", and any other UIFontTextStyle.
   5) @"Helvetica,15": fontName + fontSize, separated by comma.

 * Usages: Fnt([UIFont systemFontOfSize:15]),
           Fnt(15),
           Fnt(@15),
           Fnt(@"body"),
           Fnt(@"Helvetica,15")
 */
#define Fnt(x)  [NERUtils fontWithFontObject:NER_CONVERT_VALUE_TO_STRING(x)]

@interface UIFont (NERChainable)

@end


text:
package org.chromium.device.mojom;

import org.chromium.base.annotations.SuppressFBWarnings;
import org.chromium.mojo.bindings.DeserializationException;

public interface Sensor extends org.chromium.mojo.bindings.Interface {

    public interface Proxy extends Sensor, org.chromium.mojo.bindings.Interface.Proxy {
    }

    Manager<Sensor, Sensor.Proxy> MANAGER = Sensor_Internal.MANAGER;

    void getDefaultConfiguration(

GetDefaultConfigurationResponse callback);

    interface GetDefaultConfigurationResponse extends org.chromium.mojo.bindings.Callbacks.Callback1<SensorConfiguration> { }

    void addConfiguration(
SensorConfiguration configuration,
AddConfigurationResponse callback);

    interface AddConfigurationResponse extends org.chromium.mojo.bindings.Callbacks.Callback1<Boolean> { }

    void removeConfiguration(
SensorConfiguration configuration,
RemoveConfigurationResponse callback);

    interface RemoveConfigurationResponse extends org.chromium.mojo.bindings.Callbacks.Callback1<Boolean> { }

    void suspend(
);

    void resume(
);

}


text:
const redis = require('../redis');
const assert = require('assert');

redis.set('key','value',function(err){
    if(err){throw err;}

    redis.get('key',function(err,value){
        if(err){throw err;}

        assert.equal('value',value);

        console.log('yay it works!');

        redis.quit();
    })
});


text:
//
//  ESMensaViewController.m
//  eStudent
//
//  Created by Nicolas Autzen on 21.02.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ESFlexibleView.h"
#import "ESMensaViewController.h"
#import "foodEntry.h"
#import <QuartzCore/QuartzCore.h> //muss importiert werden, damit man runde Ecken erzeugen kann
#import "CMPopTipView.h"

static NSUInteger kNumberOfPages = 5;

@interface ESMensaViewController() <CMPopTipViewDelegate>
@property (nonatomic, strong) CMPopTipView *mensaChooseTip;
@end

@implementation ESMensaViewController

@synthesize dataManager, dateLabel, scrollView, mensaTitle, activityIndicator, pageControl, currentPage, weekday, currentDate, mensaChooseTip, essensFarbenGesetzt, dateSchouldBeChanged;

- (void)showPopTipView {
    NSString *message = @"Hier kannst du zwischen den verfügbaren Mensen wechseln";
    CMPopTipView *popTipView = [[CMPopTipView alloc] initWithMessage:message];
    popTipView.delegate = self;//delegate setzen nicht vergessen damit wir bescheidbekommen wenn der user auf den tip klickt
    popTipView.backgroundColor = [UIColor colorWithRed:.01 green:.47 blue:.94 alpha:.9];
    [popTipView presentPointingAtBarButtonItem:self.navigationItem.rightBarButtonItem animated:YES]; //inView ist immer die View in der der poptip auftauchen soll. Dies sollte eigendlich immer self.view sein
    self.mensaChooseTip = popTipView;
}

- (void)popTipViewWasDismissedByUser:(CMPopTipView *)popTipView {
// User can tap CMPopTipView to dismiss it
    self.mensaChooseTip = nil;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setBool:YES forKey:@"chooseMensaTipDisabled"];
    [defaults synchronize];
}

- (void)viewDidAppear:(BOOL)animated
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    //Fuer testzwecke zuruecksetzbar
    /*
    [defaults setBool:NO forKey:@"chooseMensaTipDisabled"];
    [defaults synchronize];
     */
    if (![defaults boolForKey:@"chooseMensaTipDisabled"]){
        [self showPopTipView];
    }
    defaults = nil;
}

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (IS_IPHONE_5) {
        self.scrollView.frame = CGRectMake(0.0, 35.0, 320.0, 449.0);
        self.pageControl.frame = CGRectMake(self.pageControl.frame.origin.x, 475.0, self.pageControl.frame.size.width, self.pageControl.frame.size.height);
    }

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //setzt das Background Image
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *backgroundImage = [defaults stringForKey:@"backgroundImage"];
    self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:backgroundImage]];
    self.essensFarbenGesetzt = [defaults boolForKey:@"essensFarben"];
    self.dateSchouldBeChanged = YES;

    NSDate *today = [NSDate date];
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:today];
    self.weekday = [components weekday];
    self.currentDate = today;

    [self.activityIndicator startAnimating];

    if (![self isWeekend]) //prüft ob Wochenende ist, wenn nein werden die Essen geladen
    {
        self.dataManager = [[MensaDataManager alloc] init];
        [self.dataManager setDelegate:self];

        //Lade default Mensa aus den UserDefaults und hole die aktuellen Daten für diese
        NSString *defaultMensa = @"uni";
        //Setze Default Mensa falls diese nicht gesetzt ist...
        if (![defaults objectForKey:@"defaultMensa"]) {
            [defaults setObject:defaultMensa forKey:@"defaultMensa"];
            [defaults synchronize];
        }
        defaultMensa = [defaults objectForKey:@"defaultMensa"];
        [self.dataManager getXMLDataFromServer:defaultMensa];
        if ([defaultMensa isEqualToString:@"uni"]) {
            [self.mensaTitle setTitle:@"Uni Boulevard"];
        } else if([defaultMensa isEqualToString:@"gw2"]) {
            [self.mensaTitle setTitle:@"GW2"];
        } else if([defaultMensa isEqualToString:@"air"]) {
            [self.mensaTitle setTitle:@"Airport"];
        }  else if([defaultMensa isEqualToString:@"bhv"]) {
            [self.mensaTitle setTitle:@"Bremerhaven"];
        } else if([defaultMensa isEqualToString:@"hsb"]) {
            [self.mensaTitle setTitle:@"Neustadtwall"];
        } else if([defaultMensa isEqualToString:@"wer"]) {
            [self.mensaTitle setTitle:@"Werderstraße"];
        }
    }

    else {
        [self.activityIndicator removeFromSuperview];
        //hier das einfügen, was am Wochenende angezeigt werden soll
        self.dateLabel.text = @"";
        UILabel *weekend = [[UILabel alloc] initWithFrame:CGRectMake(20.0, 20.0, 280.0, 70.0)];
        weekend.textAlignment = UITextAlignmentCenter;
        weekend.text = @"Wochenende";
        [weekend.layer setMasksToBounds:YES];
        weekend.layer.cornerRadius = 10.0;
        weekend.layer.opacity = .9;
        [self.scrollView addSubview:weekend];
        return;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - MensaDataManagerDelegate

- (void)noDataToParse:(MensaDataManager *)sender
{
    [self.activityIndicator removeFromSuperview];
    self.dateLabel.text = @"";
    self.scrollView.contentSize = self.scrollView.frame.size;
    self.scrollView.contentOffset = CGPointMake(0, 0);

    //hier das einfügen, was angezeigt werden soll, wenn keine Daten zum Parsen vorhanden sind
    self.dateLabel.text = @"";
    [self.scrollView setUserInteractionEnabled:NO];
    UITextView *noData = [[UITextView alloc] initWithFrame:CGRectMake(20.0, 20.0, 280.0, 110.0)];
    noData.text = @"\nEs liegen momentan keine Mensa-Daten vor, bitte versuche es zu einem späteren Zeitpunkt noch einmal.";
    noData.font = [UIFont fontWithName:@"Helvetica" size:15.0f];
    noData.textAlignment = UITextAlignmentCenter;
    [noData setScrollEnabled:NO];
    [noData setEditable:NO];
    [noData.layer setMasksToBounds:YES];
    noData.layer.cornerRadius = 10.0;
    noData.layer.opacity = .9;
    [self.scrollView addSubview:noData];
    return;
}
//wird aufgerufen, wenn keine Internetverbindung vorhanden ist
- (void)noNetworkConnection:(MensaDataManager *)sender localizedError:(NSString *)errorString
{
    [self.activityIndicator removeFromSuperview];
    self.dateLabel.text = @"";
    self.scrollView.contentSize = self.scrollView.frame.size;
    self.scrollView.contentOffset = CGPointMake(0, 0);

    //hier das einfügen, was angezeigt werden soll, wenn keine Daten zum Parsen vorhanden sind
    self.dateLabel.text = @"";
    [self.scrollView setUserInteractionEnabled:NO];

    UITextView *noNetworkConnection = [[UITextView alloc] initWithFrame:CGRectMake(20.0, 20.0, 280.0, 120.0)];
    noNetworkConnection.text = @"\nDie Verbindung zu unseren Servern ist fehlgeschlagen, bitte überprüfe deine Internetverbindung und versuche es dann noch einmal.";
    noNetworkConnection.font = [UIFont fontWithName:@"Helvetica" size:14.0f];
    noNetworkConnection.textAlignment = UITextAlignmentCenter;
    [noNetworkConnection setScrollEnabled:NO];
    [noNetworkConnection setEditable:NO];
    [noNetworkConnection.layer setMasksToBounds:YES];
    noNetworkConnection.layer.cornerRadius = 10.0;

    [self.scrollView addSubview:noNetworkConnection];
    return;
}

//Wird Aufgerufen wenn der MensaDatenManager bescheid gibt das der Datensatz zur Verfuegung steht!
- (void)mensaDataManager:(MensaDataManager *)sender loadedMenu:(NSMutableDictionary *)menu
{
    NSArray *days = [[NSArray alloc] initWithObjects:@"Montag", @"Dienstag", @"Mittwoch", @"Donnerstag", @"Freitag", nil];
    self.dateLabel.text = [NSString stringWithFormat:@"%@, %@", [days objectAtIndex:self.weekday-2], [self date:self.currentDate]];
    [self.pageControl setNumberOfPages:kNumberOfPages];

    //setzt den View auf den richtigen Tag
    self.scrollView.delegate = nil;
    self.scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * kNumberOfPages, scrollView.frame.size.height);
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.frame.size.width * (self.weekday-2), 0)];
    [self.scrollView setUserInteractionEnabled:YES];
    self.pageControl.currentPage = self.weekday-2;
    self.currentPage = self.weekday-2;

    NSMutableString *day_;
    NSEnumerator *dayEnumerator = [menu keyEnumerator];
    while (day_ = [dayEnumerator nextObject])
    {
        int positionOnScreen = 0;
        if ([day_ isEqualToString:@"Monday"]){
            positionOnScreen = 0;
        } else if ([day_ isEqualToString:@"Tuesday"]){
            positionOnScreen = 1;
        } else if ([day_ isEqualToString:@"Wednesday"]){
            positionOnScreen = 2;
        } else if ([day_ isEqualToString:@"Thursday"]){
            positionOnScreen = 3;
        } else if ([day_ isEqualToString:@"Friday"]){
            positionOnScreen = 4;
        }

        NSMutableArray *meals = [[NSMutableArray alloc] init];

        NSMutableDictionary *menuOfTheDay = [menu objectForKey:day_];
        NSMutableString *meal;
        NSEnumerator *mealEnumerator = [menuOfTheDay keyEnumerator];
        while (meal = [mealEnumerator nextObject])
        {
            [meals addObject:[menuOfTheDay objectForKey:meal]];
        }

        NSSortDescriptor *order = [[NSSortDescriptor alloc] initWithKey:@"order" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];
        NSArray *sortedMeals = [meals sortedArrayUsingDescriptors:[NSArray arrayWithObject:order]];

        [self addMealsToView:sortedMeals atPosition:positionOnScreen];
        self.scrollView.delegate = self;
        [self.activityIndicator stopAnimating];
        [self.activityIndicator removeFromSuperview];
    }
}

- (void) addMealsToView:(id)meals atPosition:(int)positionOnScreen
{
    if (positionOnScreen > kNumberOfPages || positionOnScreen < 0)
    {
        return;
    }

    CGRect frame = self.scrollView.frame;
    frame.origin.x = frame.size.width * (positionOnScreen) + 20.0;
    frame.origin.y = 5.0;
    frame.size.width -= 40.0;

    UIScrollView *mealsView = [[UIScrollView alloc] initWithFrame:frame];
    [mealsView setPagingEnabled:NO];
    [mealsView setScrollEnabled:YES];
    [mealsView setShowsVerticalScrollIndicator:NO];

    float mealPositionY = 0.0; //hier wird die Position des Essens angezeigt

    for (foodEntry *aFoodEntry in meals)
    {
        NSString *foodType; //hier wird der Essenstyp gespeichert

        UIColor *backgroundColor = [UIColor whiteColor];

        switch ([aFoodEntry.type intValue])
        {
            case 86:
                foodType = @"Vegetarisch";
                if (!self.essensFarbenGesetzt)
                {
                    backgroundColor = [UIColor colorWithRed:.81 green:1.0 blue:.694 alpha:1.0];
                }
                break;
            case 80:
                foodType = @"Vegan";
                if (!self.essensFarbenGesetzt)
                {
                    backgroundColor = [UIColor colorWithRed:.588 green:.749 blue:.533 alpha:1.0];
                }
                break;
            case 87:
                foodType = @"Wild";
                if (!self.essensFarbenGesetzt)
                {
                    backgroundColor = [UIColor colorWithRed:.909 green:.698 blue:.501 alpha:1.0];
                }
                break;
            case 83:
                foodType = @"Schwein";
                if (!self.essensFarbenGesetzt)
                {
                    backgroundColor = [UIColor colorWithRed:1.0 green:.87 blue:.862 alpha:1.0];
                }
                break;
            case 70:
                foodType = @"Fisch";
                if (!self.essensFarbenGesetzt)
                {
                    backgroundColor = [UIColor colorWithRed:.898 green:.87 blue:.866 alpha:1.0];
                }
                break;
            case 82:
                foodType = @"Rind";
                if (!self.essensFarbenGesetzt)
                {
                    backgroundColor = [UIColor colorWithRed:.749 green:.635 blue:.501 alpha:1.0];
                }
                break;
            case 71:
                foodType = @"Geflügel";
                if (!self.essensFarbenGesetzt)
                {
                    backgroundColor = [UIColor colorWithRed:1.0 green:.874 blue:.592 alpha:1.0];
                }
                break;
            case 76:
                foodType = @"Lamm";
                break;
            default:
                foodType = @"Undefiniert";
                break;
        }

        NSString *extra; //gibt es etwas extra, wird es ebenfalls hinzugefügt
        switch ([aFoodEntry.extra intValue])
        {
            case 44:
                extra = @" + Dessert";
                break;
            case 84:
                extra = @" + Tagessuppe";
                break;
            default:
                extra = @"";
                break;
        }

        // ESFlexibleView erzeugt ein UIView-Objekt, bei dem die Höhe sich flexibel an den Inhalt anpassen lässt
        ESFlexibleView *foodEntry = [[ESFlexibleView alloc] initWithX:0.0 Y:mealPositionY andWidth:280.0];
        [foodEntry.layer setMasksToBounds:YES];
        foodEntry.layer.cornerRadius = 10.0; //hiermit werden runde Ecken erzeugt.
        foodEntry.layer.opacity = .9; //hier kann die Durchsichtigkeit der Essensanzeigen gesteuert werden

        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, 280.0, 40.0)];
        [label setText:[NSString stringWithFormat:@"   %@", aFoodEntry.name]];
        //label.textColor = [UIColor colorWithRed:.2 green:.2 blue:.8 alpha:1.0];
        label.backgroundColor = backgroundColor;
        label.font = [UIFont fontWithName:@"Helvetica-Bold" size:18.0f];

        UITextView *text = [[UITextView alloc] initWithFrame:CGRectMake(35.0, 40.0, 245.0, 0.0)];
        text.backgroundColor = backgroundColor;
        [text setText:[NSString stringWithFormat:@"%@ \n\n%@%@ \n\nStudenten: %@  Mitarbeiter: %@\n",aFoodEntry.foodDescription, foodType, extra ,aFoodEntry.studentPrice, aFoodEntry.staffPrice]];

        text.font = [UIFont fontWithName:@"Helvetica" size:14.0f];

        [text setScrollEnabled:NO];
        [text setEditable:NO];

        [foodEntry addSubview:label];
        [foodEntry addSubview:text];

        //der Teil passt die Höhe des TextViews an die Menge des Inhaltes an
        CGRect frame = text.frame;
        frame.size.height = [text contentSize].height;
        text.frame = frame;

        //dient nur als Einrückung des Textes auf der linken Seite (der dritte Parameter müsste für die breite angepasst werden, dementsprechend aber auch der dritte Parameter des Essenstextes)
        UITextView *textIndent = [[UITextView alloc] initWithFrame:CGRectMake(0.0, 40.0, (280.0 - text.contentSize.width), text.contentSize.height)];
        textIndent.scrollEnabled = NO;
        textIndent.editable = NO;
        textIndent.backgroundColor = backgroundColor;
        [foodEntry addSubview:textIndent];

        [foodEntry sizeToFit]; //sizeToFit skaliert die Höhe des Views auf die Höhe des gesamten Inhaltes

        //sorgt dafür, dass ein Essen wieder die korrekte Höhe hat, nachdem der Abstand an der linken Seite eingefügt wurde
        float height = foodEntry.frame.size.height - textIndent.frame.size.height;
        foodEntry.frame = CGRectMake(foodEntry.frame.origin.x, foodEntry.frame.origin.y, 280.0, height);

        [mealsView addSubview:foodEntry];
        mealPositionY += foodEntry.frame.size.height + 10.0;
    }
    [self.scrollView addSubview:mealsView];
    mealsView.contentSize = CGSizeMake(280.0, mealPositionY);
}

#pragma mark - choose mensa

- (IBAction) chooseMensa:(id)sender
{
    UIActionSheet *chooseMensa = [[UIActionSheet alloc] initWithTitle:@"Wähle Mensa" delegate:self cancelButtonTitle:@"Abbrechen" destructiveButtonTitle:nil otherButtonTitles:@"Uni Boulevard", @"GW2", @"Airport", @"Bremerhaven", @"Neustadtwall", @"Werderstraße", nil];
    [chooseMensa showFromBarButtonItem:sender animated:YES];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *defaultMensa = [NSString stringWithString:[actionSheet buttonTitleAtIndex:buttonIndex]];
    if ([defaultMensa isEqualToString:@"Uni Boulevard"]) {
        [defaults setObject:@"uni" forKey:@"defaultMensa"];
        [self.mensaTitle setTitle:@"Uni Boulevard"];
    } else if([defaultMensa isEqualToString:@"GW2"]) {
        [defaults setObject:@"gw2" forKey:@"defaultMensa"];
        [self.mensaTitle setTitle:@"GW2"];
    } else if([defaultMensa isEqualToString:@"Airport"]) {
        [defaults setObject:@"air" forKey:@"defaultMensa"];
        [self.mensaTitle setTitle:@"Airport"];
    }  else if([defaultMensa isEqualToString:@"Bremerhaven"]) {
        [defaults setObject:@"bhv" forKey:@"defaultMensa"];
        [self.mensaTitle setTitle:@"Bremerhaven"];
    } else if([defaultMensa isEqualToString:@"Neustadtwall"]) {
        [defaults setObject:@"hsb" forKey:@"defaultMensa"];
        [self.mensaTitle setTitle:@"Neustadtwall"];
    } else if([defaultMensa isEqualToString:@"Werderstraße"]) {
        [defaults setObject:@"wer" forKey:@"defaultMensa"];
        [self.mensaTitle setTitle:@"Werderstraße"];
    }
    [defaults synchronize];

    if (![self isWeekend])
    {
        NSArray *subviews = [self.scrollView subviews];
        for (UIView *view in subviews ) {
            [view removeFromSuperview];
        }

        [self.pageControl setNumberOfPages:1];
        subviews = nil;
        self.currentDate = [NSDate date];
        self.dateSchouldBeChanged = NO;
        [self.scrollView addSubview:self.activityIndicator];
        [self.scrollView setContentOffset:CGPointMake(0, 0)];
        [self.dateLabel setText:@""];
        [self.activityIndicator startAnimating];

        self.dataManager = nil;
        self.dataManager = [[MensaDataManager alloc] init];
        self.dataManager.delegate = self;
        [self.dataManager getXMLDataFromServer:[defaults objectForKey:@"defaultMensa"]];
    }
}

#pragma mark - UIScrollViewDelegate

- (void) scrollViewDidScroll:(UIScrollView *)sender
{
    // prüft ob mehr als 50% der vorigen/nächsten Seite sichtbar sind und wechselt dann entsprechend
    CGFloat pageWidth = self.scrollView.frame.size.width;
    int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    //will man ueber Freitag hinaus nach rechts scrollen, einfach beenden, sonst stuerzt das App ab.
    if (page >= kNumberOfPages) {
        return;
    }

    self.pageControl.currentPage = page;
    int tmp = self.currentPage;
    self.currentPage = page;

    if (tmp > self.currentPage)
    {
        if (self.dateSchouldBeChanged)
        {
            //setzt das Datum einen Tag zurück
            self.currentDate = [NSDate dateWithTimeInterval:-86400 sinceDate:self.currentDate];
        }
        else
        {
            self.dateSchouldBeChanged = YES;
        }
    }
    else if (tmp < self.currentPage)
    {
        //setzt das Datum einen Tag weiter
        self.currentDate = [NSDate dateWithTimeInterval:86400 sinceDate:self.currentDate];
    }

    NSArray *days = [[NSArray alloc] initWithObjects:@"Montag", @"Dienstag", @"Mittwoch", @"Donnerstag", @"Freitag", nil];
    self.dateLabel.text = [NSString stringWithFormat:@"%@, %@", [days objectAtIndex:page], [self date:self.currentDate]];
}

#pragma mark - is Weekend

- (BOOL) isWeekend
{
    if (self.weekday > 1 && self.weekday < 7) // 1 und 7 steht für Sonntag und Samstag
    {
        return NO;
    }
    else
    {
        return YES;
    }
}

#pragma mark - Formatting the date

- (NSString *) date:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setTimeStyle:NSDateFormatterNoStyle];
    [dateFormatter setDateStyle:NSDateFormatterShortStyle];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"de_DE"]];

    return [dateFormatter stringFromDate:date];
}

#pragma mark - dealloc

- (void)dealloc
{
    self.dataManager.delegate = nil;
    self.scrollView.delegate = nil;
}

@end


text:
Pointless Button
========================

The pointless button, inspired by the [ASDF movies](http://knowyourmeme.com/memes/asdfmovie)

### Steps to use
+ Create a Phonegap / Cordova application

    `$ cordova create pointlessbutton com.example.pointlessbutton 'Pointless Button'`

+ Change directory

    `$ cd pointlessbutton/`

+ Clone this repo into the www/ folder

    `$cd www; git clone https://github.com/5uperbug/pointless-button.git`

+ Overwrite all the files

+ Add platform (Android/iOS/Windows etc)

    ```bash
    $ cordova platform add ios
    $ cordova platform add amazon-fireos
    $ cordova platform add android
    ```
+ Build the app

    `$ cordova build`

+ Run on the emulator

    `$ cordova emulate`

+ Run on the device

    `$ cordova run`


text:
from app import create_app, db
from app.models import User, Role, Permission, Post
from flask.ext.script import Manager, Shell
from flask.ext.migrate import Migrate, MigrateCommand
from os import environ

BLOG_RUNTIME = environ.get('BLOG_RUNTIME')

if BLOG_RUNTIME == ('production' or 'development' or 'testing'):
    app = create_app(BLOG_RUNTIME)
else:
    app = create_app('default')

manager = Manager(app)
migrate = Migrate(app, db)

def make_shell_context():
    return dict(app=app, db=db, User=User, Role=Role, Permission=Permission, Post=Post)
manager.add_command("shell", Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)

@manager.command
def test():
    """Run the unit tests."""
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)

if __name__ == '__main__':
    #app.run(use_reloader = False)
    manager.run()