text:
package org.jcodec.containers.flv;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

import org.jcodec.common.Codec;
import org.jcodec.common.DemuxerTrack;
import org.jcodec.common.DemuxerTrackMeta;
import org.jcodec.common.LongArrayList;
import org.jcodec.common.SeekableByteChannel;
import org.jcodec.common.SeekableDemuxerTrack;
import org.jcodec.common.model.Packet;
import org.jcodec.common.model.Size;
import org.jcodec.containers.flv.FLVTag.Type;

/**
 * This class is part of JCodec ( www.jcodec.org ) This software is distributed
 * under FreeBSD License
 *
 * Demuxer frontend for FLV, track based wrapper
 *
 * @author The JCodec project
 *
 */
public class FLVTrackDemuxer {

    private static final int MAX_CRAWL_DISTANCE_SEC = 10;

    private FLVReader demuxer;

    private FLVDemuxerTrack video;
    private FLVDemuxerTrack audio;
    private LinkedList<FLVTag> packets = new LinkedList<FLVTag>();

    private SeekableByteChannel in;

    public class FLVDemuxerTrack implements SeekableDemuxerTrack {

        private Type type;
        private int curFrame;
        private Codec codec;
        private LongArrayList framePositions = new LongArrayList();

        public FLVDemuxerTrack(Type type) throws IOException {
            this.type = type;
            FLVTag frame = nextFrameI(type, false);
            codec = frame.getTagHeader().getCodec();
        }

        @Override
        public Packet nextFrame() throws IOException {
            FLVTag frame = nextFrameI(type, true);
            framePositions.add(frame.getPosition());
            return toPacket(frame);
        }

        public Packet prevFrame() throws IOException {
            FLVTag frame = prevFrameI(type, true);
            // framePositions.add(nextFrameI.getPosition());
            return toPacket(frame);
        }

        public Packet pickFrame() throws IOException {
            FLVTag frame = nextFrameI(type, false);
            // framePositions.add(nextFrameI.getPosition());
            return toPacket(frame);
        }

        private Packet toPacket(FLVTag frame) {
            return null;
        }

        @Override
        public DemuxerTrackMeta getMeta() {
            return new DemuxerTrackMeta(type == Type.VIDEO ? DemuxerTrackMeta.Type.VIDEO : DemuxerTrackMeta.Type.AUDIO,
                    null, 0, 0, new Size(0, 0));
        }

        public Codec getCodec() {
            return codec;
        }

        @Override
        public boolean gotoFrame(long i) throws IOException {
            if (i >= framePositions.size())
                return false;
            resetToPosition(framePositions.get((int) i));
            return true;
        }

        @Override
        public boolean gotoSyncFrame(long i) {
            throw new RuntimeException();
        }

        @Override
        public long getCurFrame() {
            return curFrame;
        }

        @Override
        public void seek(double second) throws IOException {
            seekI(second);
        }
    }

    public FLVTrackDemuxer(SeekableByteChannel in) throws IOException {
        this.in = in;
        in.position(0);
        demuxer = new FLVReader(in);
        video = new FLVDemuxerTrack(Type.VIDEO);
        audio = new FLVDemuxerTrack(Type.AUDIO);
    }

    private void resetToPosition(long position) throws IOException {
        in.position(position);
        demuxer.reset();
        packets.clear();
    }

    private void seekI(double second) throws IOException {
        packets.clear();
        FLVTag base;
        while ((base = demuxer.readNextPacket()) != null && base.getPtsD() == 0)
            ;

        in.position(base.getPosition() + 0x100000);
        demuxer.reposition();
        FLVTag off = demuxer.readNextPacket();

        int byteRate = (int) ((off.getPosition() - base.getPosition()) / (off.getPtsD() - base.getPtsD()));
        long offset = base.getPosition() + (long) ((second - base.getPtsD()) * byteRate);

        in.position(offset);
        demuxer.reposition();
        // TODO: the implementation is incorrect
        // 5 reposition attempts
        for (int i = 0; i < 5; ++i) {
            FLVTag pkt = demuxer.readNextPacket();
            double distance = second - pkt.getPtsD();
            if (distance > 0 && distance < MAX_CRAWL_DISTANCE_SEC) {
                // Read to the right frame
                System.out.println("Crawling forward: " + distance);
                FLVTag testPkt;
                while ((testPkt = demuxer.readNextPacket()) != null && testPkt.getPtsD() < second)
                    ;
                if (testPkt != null)
                    packets.add(pkt);
                return;
            } else if (distance < 0 && distance > -MAX_CRAWL_DISTANCE_SEC) {
                // Read back to the frame
                System.out.println("Overshoot by: " + (-distance));
                in.position(pkt.getPosition() + (long) ((distance - 1) * byteRate));
                demuxer.reposition();
            }
        }
    }

    private FLVTag nextFrameI(Type type, boolean remove) throws IOException {
        for (Iterator<FLVTag> it = packets.iterator(); it.hasNext();) {
            FLVTag pkt = it.next();
            if (pkt.getType() == type) {
                if (remove)
                    it.remove();
                return pkt;
            }
        }
        FLVTag pkt;
        while ((pkt = demuxer.readNextPacket()) != null && pkt.getType() != type)
            packets.add(pkt);
        if (!remove)
            packets.add(pkt);

        return pkt;
    }

    private FLVTag prevFrameI(Type type, boolean remove) throws IOException {
        for (ListIterator<FLVTag> it = packets.listIterator(); it.hasPrevious();) {
            FLVTag pkt = it.previous();
            if (pkt.getType() == type) {
                if (remove)
                    it.remove();
                return pkt;
            }
        }
        FLVTag pkt;
        while ((pkt = demuxer.readPrevPacket()) != null && pkt.getType() != type)
            packets.add(0, pkt);
        if (!remove)
            packets.add(0, pkt);

        return pkt;

    }

    public DemuxerTrack[] getTracks() {
        return new DemuxerTrack[] { video, audio };
    }

    public DemuxerTrack getVideoTrack() {
        return video;
    }

    public DemuxerTrack getAudioTrack() {
        return video;
    }
}


text:
package be.wegenenverkeer.atomium.store;

import be.wegenenverkeer.atomium.api.Event;
import be.wegenenverkeer.atomium.api.EventDao;

import java.time.OffsetDateTime;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by Karel Maesen, Geovise BVBA on 05/12/16.
 */
public class StoreFixture<T> {

    private AtomicInteger counter = new AtomicInteger(0);
    final public EventDao<T> store;

    public StoreFixture() {
        this.store = new MemoryEventStore<>();
    }

    public void loadEntries(int num, T value){
        for (int i = 0; i < num; i++) {
            store.push(mkEntry(value));
        }
    }

    public Event<T> mkEntry(T val){
        return Event.make( Integer.toString(counter.getAndIncrement()) , val, OffsetDateTime.now());
    }
}

redpajama_set_name: RedPajamaGithub


text:
using DertInfo.WEB.Core;
using DertInfo.WEB.Models;
using DertInfo.WEB.ViewModels.Base;
using DertInfo.WEB.ViewModels.TeamAttendanceVMs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DertInfo.WEB.ViewModels.ResultVMs
{
    public class Graph_Listing_ByTeamAttendance_ViewModel : DertViewModelBase_Accessible
    {
        public Graph_Listing_ByTeamAttendance_ViewModel(TeamAttendance teamAttendance)
            : base(teamAttendance.AccessToken)
        {
            this.GraphByCompetitionEntryViewModelVMs = new List<GraphByCompetitionEntryViewModel>();

            this.ToView(teamAttendance);

        }

        //Properties
        public TeamAttendanceViewModel TeamAttendanceVM { get; set; }
        public List<GraphByCompetitionEntryViewModel> GraphByCompetitionEntryViewModelVMs { get; set; }

        private void ToView(TeamAttendance teamAttendance)
        {
            EventSettingRepository eventSettingRepo = new EventSettingRepository();
            EventSetting eventSetting = eventSettingRepo.FindByKey(teamAttendance.Registration.EventId, Enumerations.EventSetting.MAINCOMP_CHARACTERS_SCORECATEGORY_ID.ToString());
            //ViewData["CharactersScoreCategoryId"] = int.Parse(eventSetting.Value);

            FillBasic(teamAttendance);
            FillGraphModels(teamAttendance);
        }

        private void FillBasic(TeamAttendance teamAttendance)
        {
            this.TeamAttendanceVM = new TeamAttendanceViewModel(teamAttendance);
        }

        private void FillGraphModels(TeamAttendance teamAttendance)
        {
            ICompetitionEntryRepository competitionEntryRepo = new CompetitionEntryRepository();
            List<CompetitionEntry> competitionEntries = competitionEntryRepo.AllByTeamAttendanceId(teamAttendance.Id).ToList();

            foreach (CompetitionEntry competitionEntry in competitionEntries)
            {
                GraphByCompetitionEntryViewModel graphByCompetitionEntryVM = new GraphByCompetitionEntryViewModel(competitionEntry);
                this.GraphByCompetitionEntryViewModelVMs.Add(graphByCompetitionEntryVM);
            }
        }
    }
}


text:
"""Generate fixtures."""

import os
import json
import numpy as np
from scipy.special import exprel

# Get the file path:
FILE = os.path.realpath(__file__)

# Extract the directory in which this file resides:
DIR = os.path.dirname(FILE)

def gen(x, name):
    """Generate fixture data and write to file.

    # Arguments

    * `x`: domain
    * `name::str`: output filename

    # Examples

    ``` python
    python> x = linspace(-1000, 1000, 2001)
    python> gen(x, './data.json')
    ```
    """
    y = exprel(x)
    data = {
        "x": x.tolist(),
        "expected": y.tolist()
    }

    # Based on the script directory, create an output filepath:
    filepath = os.path.join(DIR, name)

    # Write the data to the output filepath as JSON:
    with open(filepath, "w", encoding="utf-8") as outfile:
        json.dump(data, outfile)

def main():
    """Generate fixture data."""
    # Medium negative values:
    x = np.linspace(-709.78, -1.0, 1000)
    gen(x, "medium_negative.json")

    # Medium positive values:
    x = np.linspace(1.0, 709.78, 1000)
    gen(x, "medium_positive.json")

    # Small negative values:
    x = np.linspace(-1.0, -2.0**-54, 1000)
    gen(x, "small_negative.json")

    # Small positive values:
    x = np.linspace(2.0**-54, 1.0, 1000)
    gen(x, "small_positive.json")

    # Tiny values:
    x = np.linspace(-2.0**-54, 2.0**-54, 1000)
    gen(x, "tiny.json")

if __name__ == "__main__":
    main()


text:
package sun.jvm.hotspot.utilities;

import sun.jvm.hotspot.oops.*;

/** Describes an element in a {@link
    sun.jvm.hotspot.utilities.LivenessPath}. It indicates that the
    field in the given object leads to the next element in the
    path. Root elements do not have an object; the terminal element in
    the path does not have a field identifier. */

public class LivenessPathElement {
  LivenessPathElement(Oop obj, FieldIdentifier id) {
    this.obj = obj;
    this.id  = id;
  }

  public boolean isRoot() {
    return (obj == null);
  }

  public boolean isTerminal() {
    return (id == null);
  }

  public Oop getObj() {
    return obj;
  }

  public FieldIdentifier getField() {
    return id;
  }

  //---------------------------------------------------------------------------
  // Internals only below this point
  //
  private Oop             obj;
  private FieldIdentifier id;
}


text:
package cn.gavinliu.notificationbox.widget;

import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Created by Gavin on 2016/10/12.
 */

public abstract class BaseViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    public BaseViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

    }
}


text:
import React from 'react';
import PropTypes from 'prop-types';

import './Todo.css';

const Todo = ({ onClick, completed, text }) => (
    <li
        onClick={onClick}
        className={completed ? 'completed' : ''}
    >
        <input type="checkbox" className="toggle" checked={completed} />
        <label>{text}</label>
    </li>
);

Todo.propTypes = {
    onClick: PropTypes.func.isRequired,
    completed: PropTypes.bool.isRequired,
    text: PropTypes.string.isRequired
};

export default Todo;


text:
package org.durid.sql.ast.statement;

import org.durid.sql.visitor.SQLASTVisitor;

public class SQLSubqueryTableSource extends SQLTableSourceImpl {

    private static final long serialVersionUID = 1L;

    protected SQLSelect       select;

    public SQLSubqueryTableSource(){

    }

    public SQLSubqueryTableSource(String alias){
        super(alias);
    }

    public SQLSubqueryTableSource(SQLSelect select, String alias){
        super(alias);
        this.select = select;
    }

    public SQLSubqueryTableSource(SQLSelect select){

        this.select = select;
    }

    public SQLSelect getSelect() {
        return this.select;
    }

    public void setSelect(SQLSelect select) {
        this.select = select;
    }

    @Override
    protected void accept0(SQLASTVisitor visitor) {
        if (visitor.visit(this)) {
            acceptChild(visitor, select);
        }
        visitor.endVisit(this);
    }

    public void output(StringBuffer buf) {
        buf.append("(");
        this.select.output(buf);
        buf.append(")");
    }

	@Override
	public String getTablename() {
		return null;
	}
}


text:
package org.drools.workbench.screens.guided.template.server.indexing;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.concurrent.NotThreadSafe;

import org.apache.lucene.search.Query;
import org.drools.workbench.models.guided.template.backend.RuleTemplateModelXMLPersistenceImpl;
import org.drools.workbench.models.guided.template.shared.TemplateModel;
import org.drools.workbench.screens.guided.template.type.GuidedRuleTemplateResourceTypeDefinition;
import org.guvnor.common.services.project.categories.Decision;
import org.junit.Test;
import org.kie.soup.project.datamodel.imports.Import;
import org.kie.workbench.common.services.refactoring.backend.server.BaseIndexingTest;
import org.kie.workbench.common.services.refactoring.backend.server.TestIndexer;
import org.kie.workbench.common.services.refactoring.backend.server.query.builder.SingleTermQueryBuilder;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueIndexTerm.TermSearchType;
import org.kie.workbench.common.services.refactoring.model.index.terms.valueterms.ValueSharedPartIndexTerm;
import org.kie.workbench.common.services.refactoring.service.PartType;
import org.uberfire.ext.metadata.io.KObjectUtil;
import org.uberfire.java.nio.file.Path;

@NotThreadSafe
public class IndexGuidedRuleTemplateAttributesTest extends BaseIndexingTest<GuidedRuleTemplateResourceTypeDefinition> {

    @Test
    public void testIndexGuidedRuleTemplateAttributes() throws IOException, InterruptedException {
        //Add test files
        final Path path = basePath.resolve("template1.template");
        final TemplateModel model = GuidedRuleTemplateFactory.makeModelWithAttributes("org.drools.workbench.screens.guided.template.server.indexing",
                                                                                new ArrayList<Import>() {{
                                                                                add(new Import("org.drools.workbench.screens.guided.template.server.indexing.classes.Applicant"));
                                                                                add(new Import("org.drools.workbench.screens.guided.template.server.indexing.classes.Mortgage"));
                                                                                }},
                                                                                "template1");
        final String xml = RuleTemplateModelXMLPersistenceImpl.getInstance().marshal(model);
        ioService().write(path,
                          xml);

        Thread.sleep(5000); //wait for events to be consumed from jgit -> (notify changes -> watcher -> index) -> lucene index

        List<String> index = Arrays.asList(KObjectUtil.toKCluster(basePath.getFileSystem()).getClusterId());

        {
            final Query query = new SingleTermQueryBuilder(new ValueSharedPartIndexTerm("*", PartType.RULEFLOW_GROUP, TermSearchType.WILDCARD))
                    .build();
            searchFor(index, query, 1, path);
        }

        //Rule Template defining a RuleFlow-Group named myRuleFlowGroup. This should match template1.template
        //This checks whether there is a Rule Attribute "ruleflow-group" and its Value is "myRuleflowGroup"
        {
            final Query query = new SingleTermQueryBuilder(new ValueSharedPartIndexTerm("myRuleFlowGroup", PartType.RULEFLOW_GROUP))
                    .build();
            searchFor(index, query, 1, path);
        }
    }

    @Override
    protected TestIndexer getIndexer() {
        return new TestGuidedRuleTemplateFileIndexer();
    }

    @Override
    protected GuidedRuleTemplateResourceTypeDefinition getResourceTypeDefinition() {
        return new GuidedRuleTemplateResourceTypeDefinition(new Decision());
    }

    @Override
    protected String getRepositoryName() {
        return this.getClass().getSimpleName();
    }
}


text:
import sys

sys.path.append("../util")
import Util
from Util import ConfigInfo
import unittest
import ghLogDb

class ghLogDbTest(unittest.TestCase):

    def setUp(self):

        c_info = ConfigInfo("../util/sample_conf.ini")
        c_info2 = ConfigInfo("../util/javatest.ini")
        Util.DATABASE = 0
        self.testCommit1 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit1.txt",c_info)
        self.testCommit2 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit2.txt",c_info)
        self.testCommit3 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit3.txt",c_info)
        self.testCommit4 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit4.txt",c_info)
        self.testCommit5 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit5.txt",c_info)

        self.testCommit7 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit7.txt",c_info)
        #self.testCommit8 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit8.txt",c_info) #Broken, but I don't think its fixable. Fault of git logger
        self.testCommit9 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit9.txt",c_info)
        self.testCommit10 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit10.txt",c_info)
        self.testCommit11 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit11.txt",c_info)
        self.testCommit12 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit12.txt",c_info)
        self.testCommit13 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit13.txt",c_info)
        self.testCommit14 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit14.txt",c_info)
        self.testCommit15 = ghLogDb.ghLogDb("testfiles/ghLogDbTest/TestCommit15.txt",c_info)

        #self.testCommit13.processLog() #Make sure there is no crash -> Hangs a long time

        self.testCommitb1=ghLogDb.ghLogDb("testfiles/ghLogDbTestBlock/TestCommit1.txt",c_info2)

    def test_Commit1(self):
        self.testCommit1.processLog()
        shas = self.testCommit1.shas
        #self.assertTrue(len(shas) == 1) #Just 1 commit.
        self.assertTrue(shas[0].author == "Liu Liu")
        patches = shas[0].patches
        self.assertTrue(len(patches) == 4)
        for patch in patches:
            self.assertTrue(patch.language == "c")
            self.assertTrue(patch.is_test == False)
            print(patch.file_name)

        self.assertTrue(patches[0].file_name == "bin/cuda/cwc-verify.c")
        methods = patches[0].methods
        self.assertTrue(len(methods) == 2)

        self.assertTrue(methods[0].method == "main")
        self.assertTrue(methods[0].total_add == 1)
        self.assertTrue(methods[0].total_del == 1)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[0].keywordDictionary)

        self.assertTrue(methods[1].method == "GITCPROC_NON_FUNCTION")
        self.assertTrue(methods[1].total_add == 1)
        self.assertTrue(methods[1].total_del == 1)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[1].keywordDictionary)

        self.assertTrue(patches[1].file_name == "bin/image-net.c")
        methods = patches[1].methods
        self.assertTrue(len(methods) == 1)
        self.assertTrue(methods[0].method == "main")
        self.assertTrue(methods[0].total_add == 8)
        self.assertTrue(methods[0].total_del == 8)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[0].keywordDictionary)

        self.assertTrue(patches[2].file_name == "lib/ccv_convnet.c")
        methods = patches[2].methods
        self.assertTrue(len(methods)==7)
        self.assertTrue(methods[1].method == "ccv_convnet_verify")
        self.assertTrue(methods[1].total_add == 6)
        self.assertTrue(methods[1].total_del == 0)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[1].keywordDictionary)
        self.assertTrue(patches[3].file_name == "lib/ccv_icf.c")
        methods = patches[3].methods
        self.assertTrue(len(methods)==1)

    def test_Commit2(self):
        self.testCommit2.processLog()
        shas = self.testCommit2.shas
        #self.assertTrue(len(shas) == 1) #Just 1 commit.
        self.assertTrue(shas[0].author == "Liu Liu")
        patches = shas[0].patches
        self.assertTrue(len(patches) == 2)
        for patch in patches:
            self.assertTrue(patch.language == "c")
            self.assertTrue(patch.is_test == False)
            print(patch.file_name)

        self.assertTrue(patches[0].file_name == "bin/cuda/cwc-bench.c")
        methods = patches[0].methods
        self.assertTrue(len(methods) == 1)
        self.assertTrue(methods[0].method == "main")
        self.assertTrue(methods[0].total_add == 43)
        self.assertTrue(methods[0].total_del == 5)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[0].keywordDictionary)

        self.assertTrue(patches[1].file_name == "bin/cuda/cwc-verify.c")
        methods = patches[1].methods

        self.assertTrue(len(methods) == 2)
        self.assertTrue(methods[0].method == "main")
        self.assertTrue(methods[0].total_add == 314)
        self.assertTrue(methods[0].total_del == 0)
        testDict = {'assert Adds':1, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[0].keywordDictionary)

        self.assertTrue(methods[1].method == "GITCPROC_NON_FUNCTION")
        self.assertTrue(methods[1].total_add == 6)
        self.assertTrue(methods[1].total_del == 0)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[1].keywordDictionary)

    def test_Commit3(self):
        self.testCommit3.processLog()
        shas = self.testCommit3.shas
        #self.assertTrue(len(shas) == 1) #Just 1 commit.
        self.assertTrue(shas[0].author == "Liu Liu")
        patches = shas[0].patches
        self.assertTrue(len(patches) == 1)
        for patch in patches:
            self.assertTrue(patch.language == "c")
            self.assertTrue(patch.is_test == False)
            print(patch.file_name)

        self.assertTrue(patches[0].file_name == "lib/ccv_convnet.c")
        methods = patches[0].methods
        self.assertTrue(len(methods) == 2)

        self.assertTrue(methods[0].method == "_ccv_convnet_convolutional_forward_propagate_sse2")
        self.assertTrue(methods[0].total_add == 1)
        self.assertTrue(methods[0].total_del == 1)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[0].keywordDictionary)

        self.assertTrue(methods[1].method == "_ccv_convnet_convolutional_forward_propagate_neon")

        self.assertTrue(methods[1].total_add == 62)
        self.assertTrue(methods[1].total_del == 40)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[1].keywordDictionary)

    def test_Commit4(self):
        self.testCommit4.processLog()
        shas = self.testCommit4.shas
        #self.assertTrue(len(shas) == 1) #Just 1 commit.
        self.assertTrue(shas[0].author == "Liu Liu")
        patches = shas[0].patches
        self.assertTrue(len(patches) == 2)
        for patch in patches:
            self.assertTrue(patch.language == "c")
            self.assertTrue(patch.is_test == False)
            print(patch.file_name)

        methods = patches[0].methods
        self.assertTrue(len(methods) == 1)

        self.assertTrue(methods[0].method == "ccv_gemm")
        self.assertTrue(methods[0].total_add == 2)
        self.assertTrue(methods[0].total_del == 0)
        testDict = {'assert Adds':1, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[0].keywordDictionary)

        methods = patches[1].methods
        self.assertTrue(len(methods) == 4)
        self.assertTrue(methods[0].method == "_ccv_convnet_compute_softmax")
        self.assertTrue(methods[0].total_add == 0)
        self.assertTrue(methods[0].total_del == 18)
        testDict = {'assert Adds':0, 'assert Dels': 1, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[0].keywordDictionary)

        self.assertTrue(methods[1].method == "GITCPROC_NON_FUNCTION")
        self.assertTrue(methods[1].total_add == 0)
        self.assertTrue(methods[1].total_del == 2)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[1].keywordDictionary)

        self.assertTrue(methods[2].method == "_ccv_convnet_compute_softmax")
        self.assertTrue(methods[2].total_add == 18)
        self.assertTrue(methods[2].total_del == 0)
        testDict = {'assert Adds':1, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[2].keywordDictionary)

        self.assertTrue(methods[3].method == "GITCPROC_NON_FUNCTION")
        self.assertTrue(methods[3].total_add == 2)
        self.assertTrue(methods[3].total_del == 0)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[3].keywordDictionary)

    def test_Commit5(self):
        self.testCommit5.processLog()
        shas = self.testCommit5.shas
        #self.assertTrue(len(shas) == 1) #Just 1 commit.
        self.assertTrue(shas[0].author == "Lars Op den Kamp")
        patches = shas[0].patches
        self.assertTrue(len(patches) == 2)

        for patch in patches:
            self.assertTrue(patch.language == "cpp")
            self.assertTrue(patch.is_test == False)
            print(patch.file_name)

        methods = patches[0].methods
        self.assertTrue(len(methods) == 8)
        self.assertTrue(methods[3].method == "*dlopen")
        self.assertTrue(methods[3].total_add == 66)
        self.assertTrue(methods[3].total_del == 0)
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        # self.assertEqual(testDict,methods[3].keywordDictionary)

        methods = patches[1].methods
        self.assertTrue(len(methods) == 9)

    def test_Commit7(self):
        self.testCommit7.processLog()
        shas = self.testCommit7.shas
        #self.assertTrue(len(shas) == 1) #Just 1 commit.
        self.assertTrue(shas[0].author == "Dmitry Lenev")
        patches = shas[0].patches
        #print(patches)
        #patch[0].printPatch()
        self.assertTrue(len(patches) == 1)

        methods = patches[0].methods
        #print(len(methods))
        #print(methods)
        #2 non-functions b/c we get 1 for each @@ where there are changes outside a function
        self.assertTrue(len(methods) == 11)

#    def test_commit8(self):
#        self.testCommit8.processLog()
#        shas = self.testCommit8.shas
#        #self.assertTrue(len(shas) == 1)
#        self.assertTrue(shas[0].author == "Sunny Bains")
#        patches = shas[0].patches
#
#        self.assertTrue(len(patches) == 1)
#
#        methods = patches[0].methods
#        self.assertTrue(len(methods) == 4)
#
#        self.assertTrue(methods[0].method == "innobase_next_autoinc")
#        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_a Adds':9, 'ut_a Dels': 4, 'ut_ad Adds':0, 'ut_ad Dels': 0}
#        self.assertEqual(testDict,methods[0].keywordDictionary)
#
#        self.assertTrue(methods[1].method == "ha_innobase::innobase_initialize_autoinc")
#        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
#        self.assertEqual(testDict,methods[1].keywordDictionary)
#
#        self.assertTrue(methods[2].method == "ha_innobase::update_row")
#        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
#        self.assertEqual(testDict,methods[2].keywordDictionary)
#
#        self.assertTrue(methods[3].method == "ha_innobase::get_auto_increment")
#        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
#        self.assertEqual(testDict,methods[3].keywordDictionary)

    def test_commit9(self):
        self.testCommit9.processLog()
        shas = self.testCommit9.shas
        #self.assertTrue(len(shas) == 1)
        self.assertTrue(shas[0].author == "davi@mysql.com/endora.local") #It doesn't recognize this?
        patches = shas[0].patches

        self.assertTrue(len(patches) == 1)

        methods = patches[0].methods
        #Three non functions
        self.assertTrue(len(methods) == 13)

        self.assertTrue(methods[8].method == "mysql_stmt_close")
        testDict = {'assert Adds':1, 'assert Dels': 1, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[8].keywordDictionary)

    def test_commit10(self):
        self.testCommit10.processLog()
        shas = self.testCommit10.shas
        #self.assertTrue(len(shas) == 1)
        self.assertTrue(shas[0].author == "Liu Liu")
        patches = shas[0].patches

        self.assertTrue(len(patches) == 5)

        methods = patches[3].methods
        self.assertTrue(len(methods) == 8) #One non function

        self.assertTrue(methods[0].method == "_ccv_read_rgb_raw")
        testDict = {'assert Adds':2, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[0].keywordDictionary)

        methods = patches[4].methods
        self.assertTrue(len(methods) == 1) #Can't match the test case macros, so only the nonfunction
        self.assertTrue(methods[0].method == "GITCPROC_NON_FUNCTION")

    def test_commmit11(self):
        self.testCommit11.processLog() #Make sure there is no crash

    def test_commmit12(self):
        self.testCommit12.processLog() #Make sure there is no crash

    def test_commmit14(self):
        self.testCommit14.processLog() #This was not being written out. Why?
        shas = self.testCommit14.shas
        self.assertTrue(len(shas) == 1)
        self.assertTrue(shas[0].author == "Jonathan Tang")
        patches = shas[0].patches

        self.assertTrue(len(patches) == 1)
        methods = patches[0].methods
        self.assertTrue(len(methods) == 1)

        self.assertTrue(methods[0].method == "GITCPROC_NON_FUNCTION")
        testDict = {'assert Adds':0, 'assert Dels': 0, 'ut_ad Adds':0, 'ut_ad Dels': 0, 'ut_a Adds':0, 'ut_a Dels': 0}
        self.assertEqual(testDict,methods[0].keywordDictionary)

    def test_commmit15(self):
        self.testCommit15.processLog() #Make sure there is no crash

    def test_Commitb1(self):
        self.testCommitb1.processLog()
        shas = self.testCommitb1.shas
        #self.assertTrue(len(shas) == 1) #Just 1 commit.
        self.assertTrue(shas[0].author == "Kevin Sawicki")
        patches = shas[0].patches
        self.assertTrue(len(patches) == 1)
        for patch in patches:
            self.assertTrue(patch.language == "java")
            self.assertTrue(patch.is_test == False)
            print(patch.file_name)

        self.assertTrue(patches[0].file_name == "app/src/main/java/com/github/mobile/accounts/AccountUtils.java")
        methods = patches[0].methods

        self.assertTrue(len(methods) == 1)
        self.assertTrue(methods[0].method == "getAccounts")
        self.assertTrue(methods[0].total_add == 1)
        self.assertTrue(methods[0].total_del == 2)
        dict= {'throw Adds':0, 'catch Dels': 0, 'throw Dels': 0, 'try Adds': 0, 'try Dels': 0, 'exception Dels': 0, 'raise Adds': 0, 'catch Adds': 0, 'finally Dels': 0, 'finally Adds': 0, 'exception Adds': 0, 'raise Dels': 0, 'for Adds': 0,'for Dels': 0,'while Adds': 0,'while Dels': 0}
        self.assertEqual(dict,methods[0].keywordDictionary)

if __name__=="__main__":
    unittest.main()


text:
<?xml version="1.0" encoding="utf-8"?>

<!--

-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/advancedPad"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/sin"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:hint="@string/arcsin"
            android:text="@string/sin" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/cos"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:hint="@string/arccos"
            android:text="@string/cos" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/tan"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:hint="@string/arctan"
            android:text="@string/tan" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/i"
            style="@style/Theme.Calculator.ButtonStyle"
            android:text="@string/i" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/ln"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/ln" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/lg"
            style="@style/Theme.Calculator.ButtonStyle.Small"
            android:text="@string/lg" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/pi"
            style="@style/Theme.Calculator.ButtonStyle"
            android:text="@string/pi" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/e"
            style="@style/Theme.Calculator.ButtonStyle"
            android:text="@string/e" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/percentage"
            style="@style/Theme.Calculator.ButtonStyle"
            android:text="@string/percentage" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/factorial"
            style="@style/Theme.Calculator.ButtonStyle"
            android:text="@string/factorial" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/sqrt"
            style="@style/Theme.Calculator.ButtonStyle"
            android:hint="@string/cbrt"
            android:text="@string/sqrt" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/power"
            style="@style/Theme.Calculator.ButtonStyle"
            android:text="@string/power" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/leftParen"
            style="@style/Theme.Calculator.ButtonStyle"
            android:text="@string/leftParen" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/rightParen"
            style="@style/Theme.Calculator.ButtonStyle"
            android:text="@string/rightParen" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/X"
            style="@style/Theme.Calculator.ButtonStyle.Digit"
            android:text="@string/X" />

        <com.android2.calculator3.view.ColorButton
            android:id="@+id/Y"
            style="@style/Theme.Calculator.ButtonStyle.Digit"
            android:text="@string/Y" />
    </LinearLayout>
</LinearLayout>


text:
This template deploys resources required to host Kentico MVC environments in Microsoft Azure.

[Kentico](https://www.kentico.com) is an all-in-one content management, E-commerce, and Online Marketing platform that drives business results for companies of all sizes, both on-premise or in the cloud. It gives customers and partners powerful, comprehensive tools and customer-centric solutions to create stunning websites and manage customer experiences easily in a dynamic business environment.

Kentico supports website development using ASP.NET MVC 5. The support is based on a separate MVC application while Kentico runs in a different application that you use as a content platform.

Both Kentico and the MVC application access data from the same database and use the Kentico API. Web farms handle content synchronization of smart search indexes and other data. This approach allows the live site (MVC application) and the administration (Kentico) to exist separately, providing finer control over each website's presentation layer.

`Tags: Kentico, cms, MVC, content management, e-commerce, online marketing`

## Deployed resources

The template deploys the following resources:

### Microsoft.Sql

Deploys an Azure SQL server with the specified configuration.

The deployed SQL server by default only allows connections from other Azure resources. To allow connections from non-Azure services or environments, you need to set custom firewall rules.

#### Deployed resources:

+ **Azure SQL Server**: An Azure SQL Server instance

### Microsoft.Web

Deploys and configures two Azure App Service Web Apps, each with a separate hosting plan (allowing for independent scale-out of both applications to multiple instances). In most cases, the MVC application will receive the bulk of the traffic and have different performance requirements than the administration interface.

Furthermore, if deployed to an App Service plan with a pricing tier of *S1* or higher, the Web App hosting the MVC application is configured to automatically scale out to up to two instances when necessary via the 'Autoscale' feature. Note that using 'Autoscale' may require you to reconfigure the MVC application's session state storage to account for multiple applications. See [Storing session state data in an Azure Environment](https://kentico.com/CMSPages/DocLinkMapper.ashx?version=latest&link=azure_state_storing) in the Kentico documentation.

#### Deployed resources:

+ **Administration App Service Plan:** An App Service plan housing the Kentico administration application
+ **Live-site App Service Plan:** An App Service plan housing the MVC front-end application
+ **Azure App Service front-end Web App:** A Web App hosting the MVC front-end application
+ **Azure App Service administration Web App:** A Web App hosting the Kentico Administration application

### Microsoft.Insights

Deploys Application Insights for the MVC application.

#### Deployed resources:

+ **Application Insights:** An Application Insights service that provides performance monitoring for the Web App hosting the MVC application.

## Usage

You can use this template to configure and deploy resources necessary to host a Kentico MVC environment in Azure. A recommended development process follows these general steps:

1. [Develop](https://kentico.com/CMSPages/DocLinkMapper.ashx?version=latest&link=mvc_development) a Kentico MVC project locally.
2. Use this template to deploy resources necessary to host the Kentico MVC site in Azure (click *Deploy to Azure* at the top of this document).
	- See the **Deployed resources** section for an overview of all resources deployed by the template.
3. [Publish](https://kentico.com/CMSPages/DocLinkMapper.ashx?version=latest&link=azure_webapps_deploying_mvc) the Kentico administration and MVC front-end applications to the deployed Web Apps.
4. Upload the project's database to a database created under the Azure SQL server instance deployed by the template.

For more information about MVC development and general best practices, visit the [Kentico documentation](https://docs.kentico.com).

## Deployment steps

 1. Click the "**Deploy** to Azure" button at the top of this document.
 2. Under basics, select your Azure subscription, resource group, and resource location.
 3. Under settings, provide the information required to deploy Azure services used to host your Kentico MVC site.
	 - You are free to modify all provided default values **except** for the **Location** setting. Modifying the **Location** setting's value may cause issues during the template deployment.
4. Agree with the displayed terms and conditions and click **Purchase**.
	- The template deploys all resources necessary to host Kentico MVC sites in Microsoft Azure.
5. Deploy your local database and MVC and Kentico administration sites to the created Azure SQL server and Web Apps.
	- For step-by-step instructions detailing this process, visit the [Kentico documentation](https://kentico.com/CMSPages/DocLinkMapper.ashx?version=latest&link=azure_webapps_deploying_mvc).

### Additional database installation

If you did not specify the *Connection String Database Name* setting during the ARM template deployment, the template creates both Web App instances without pre-configured connection strings.

You can specify the connection strings after deployment in **Azure Portal -> App Services -> Your Web App -> Configuration**. Add the connection strings in the following format:

`Name: CMSConnectionString`

`Value: Data Source=tcp:<SQL_SERVER_NAME>.database.windows.net,1433;Initial Catalog=<DATABASE_NAME>;User Id=<USER_NAME>@<SQL_SERVER_NAME>;Password=<USER_PASSWORD>;`

`Type: SQLServer`

Substitute the *<SQL_SERVER_NAME>*, *<DATABASE_NAME>*, *<USER_NAME>*, and *<USER_PASSWORD>* placeholders with the information you provided during template deployment.


text:
source ../common/common.sh

NAME=Cython
GIT_REPO=git@github.com:cython/cython.git

init_vars

checkout_git

pushd "${BUILD_DIR}"
module load anaconda3
export PYTHONPATH="${INSTALL_DIR}/${PYTHON3_PACKAGE_SUBDIR}:${PYTHONPATH}"
mkdir -p "${INSTALL_DIR}/${PYTHON3_PACKAGE_SUBDIR}"
python3 setup.py install --prefix="${INSTALL_DIR}"
popd

DESC="Theano computation library"
HELP="Installs Theano library for Python"
BIN_PATH="${INSTALL_DIR}/bin"

read -d '' EXTRA_LINES <<EOF || true
module add      anaconda3
append-path     PYTHONPATH ${INSTALL_DIR}/${PYTHON3_PACKAGE_SUBDIR}
EOF

write_module

rm -rf "${BUILD_DIR}"


text:
package io.cucumber.pro.config.loaders;

import java.util.HashMap;

public class SystemPropertiesConfigLoaderTest extends ConfigLoaderContract {
    @Override
    protected ConfigLoader makeConfigLoader() {
        return new SystemPropertiesConfigLoader(new HashMap<Object, Object>() {{
            put("cucumber.format", "progress");
        }});
    }
}


text:
package de.gessnerfl.rabbitmq.queue.management.service.json;

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

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import com.google.gson.Gson;

class JsonSerializerTest {
    private final static String JSON = "{\"myString\":\"test\",\"myNumber\":123}";

    private JsonSerializer sut;

    @BeforeEach
    void init() {
        sut = new JsonSerializer(new Gson());
    }

    @Test
    void shouldSerializeToJson() {
        Dummy dummy = new Dummy("test", 123);

        String result = sut.toJson(dummy);

        assertEquals(JSON, result);
    }

    @Test
    void shouldDeserializeFromJson() {
        Dummy result = sut.fromJson(Dummy.class, JSON);

        assertEquals("test", result.myString);
        assertEquals(123, result.myNumber);
    }

    private class Dummy {
        final String myString;
        final int myNumber;

        Dummy(String myString, int myNumber) {
            this.myString = myString;
            this.myNumber = myNumber;
        }
    }
}


text:
@interface RGViewController : UIViewController

- (IBAction)showShortToast:(id)sender;
- (IBAction)showLongToast:(id)sender;
- (IBAction)showManyShortToasts:(id)sender;
- (IBAction)showManyLongToasts:(id)sender;

@end


text:
{% extends 'imagersite/base.html' %}

{% block body %}

Edit Album

      <form action="" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit" class="btn btn-primary">Update photo</button>
      </form>

{% endblock %}


text:
module Chaskiq
  module Manage::CampaignsHelper

    def metric_action_class(metric)
      case metric.action
      when "deliver"
        "plain"
      when "open"
        "info"
      when "click"
        "primary"
      when "bounce"
        "warning"
      when "spam"
        "danger"
      end
    end

    def metric_icon_action_class(metric)
      case metric.action
      when "deliver"
        "check"
      when "open"
        "check"
      when "click"
        "check"
      when "bounce"
        "exclamation"
      when "spam"
        "exclamation-triangle"
      end
    end

  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package de.christofreichardt.diagnosis;

import de.christofreichardt.diagnosis.io.IndentablePrintStream;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import org.w3c.dom.Node;

/**
 * <div style="text-align: justify">
 * A special tracer intended for the use by a bounded blocking queue. This is an option to retrieve tracer within a multi-threaded environment
 * when we cannot control the creation of the threads. An example would be applications within a container that manages a thread pool. This tracer
 * honors the contract of an {@link AbstractTracer} but does so by wrapping and delegating to another {@link AbstractTracer}. In particular the
 * current tracing context will be automatically cleared when calling {@link #wayout()} and the method stack remains empty afterwards. Thus the tracer
 * can be reused for another thread's tracing context without any danger to create a memory leak.
 * </div>
 *
 * @author Christof Reichardt
 * @param <T> the wrapped tracer
 */
abstract public class QueueTracer<T extends AbstractTracer> extends AbstractTracer {

  private boolean online;
  private int level;

  /**
   * Some tracer.
   */
  final protected T tracer;

  /**
   * Constructor expects the tracer name and the to be wrapped tracer instance.
   *
   * @param name the name of the tracer
   * @param tracer the to be wrapped tracer
   */
  public QueueTracer(String name, T tracer) {
    super(name);
    this.tracer = tracer;
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @return the sync object of the wrapped tracer
   */
  @Override
  public Object getSyncObject() {
    return this.tracer.getSyncObject();
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @return the buffer size of the wrapped tracer
   */
  @Override
  public int getBufferSize() {
    return this.tracer.getBufferSize();
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @return indicates the autoflush mode of the wrapped tracer
   */
  @Override
  public boolean isAutoflush() {
    return this.tracer.isAutoflush();
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @return indicates if the wrapped tracer is openend
   */
  @Override
  public boolean isOpened() {
    return this.tracer.isOpened();
  }

//  /**
//   *
//   * @return
//   */
//  @Override
//  public String getName() {
//    return this.tracer.getName();
//  }

  /**
   * Sets the buffer size of the wrapped tracer.
   *
   * @param bufferSize the bufferSize to set
   */
  @Override
  public void setBufferSize(int bufferSize) {
    this.tracer.setBufferSize(bufferSize);
  }

  /**
   * Sets the autoflush mode of the wrapped tracer
   * @param autoflush the autoflush to set
   */
  @Override
  protected void setAutoflush(boolean autoflush) {
    this.tracer.setAutoflush(autoflush);
  }

  @Override
  protected void readConfiguration(XPath xpath, Node node) throws XPathExpressionException, AbstractTracer.Exception {
    this.online = (boolean) xpath.evaluate("./dns:Online/text()", node, XPathConstants.BOOLEAN);
    this.level = Integer.parseInt((String) xpath.evaluate("./dns:DebugLevel/text()", node, XPathConstants.STRING));
    setAutoflush((boolean) xpath.evaluate("./dns:TraceLogger/dns:AutoFlush/text()", node, XPathConstants.BOOLEAN));
    setBufferSize(Integer.parseInt((String) xpath.evaluate("./dns:TraceLogger/dns:BufSize/text()", node, XPathConstants.STRING)));
  }

  /**
   * Opens the wrapped tracer.
   */
  @Override
  public void open() {
    this.tracer.open();
  }

  /**
   * Closes the wrapped tracer.
   */
  @Override
  public void close() {
    this.tracer.close();
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer by using the config parameter global
   * to all queued tracer.
   */
  @Override
  public void initCurrentTracingContext() {
    this.tracer.initCurrentTracingContext(this.level, this.online);
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @param debugLevel controls the extent of the output
   * @param online a value of false delivers no output of the current thread at all whereas a value of true delivers output controlled by debugLevel
   */
  @Override
  public void initCurrentTracingContext(int debugLevel, boolean online) {
    this.tracer.initCurrentTracingContext(debugLevel, online);
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @param returnType the return type of the method as string representation
   * @param clazz the class to which that method belong
   * @param methodSignature the remaining method signature (without return type) inclusive parameter as string representation
   * @return the TraceMethod which has been put onto the stack - a mere data object for internal use primarily. May be null.
   */
  @Override
  public TraceMethod entry(String returnType, Class clazz, String methodSignature) {
    return this.tracer.entry(returnType, clazz, methodSignature);
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @param returnType the return type of the method as string representation
   * @param object the object that owns the method
   * @param methodSignature the remaining method signature (without return type) inclusive parameter as string representation
   * @return the TraceMethod which has been put onto the stack - a mere data object for internal use primarily. May be null.
   */
  @Override
  public TraceMethod entry(String returnType, Object object, String methodSignature) {
    return this.tracer.entry(returnType, object, methodSignature);
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @param logLevel one of the predefined levels INFO, WARNING, ERROR, FATAL and SEVERE
   * @param message the to be logged message
   * @param clazz the originating class
   */
  @Override
  public void logMessage(LogLevel logLevel, String message, Class clazz, String methodName) {
    this.tracer.logMessage(logLevel, message, clazz, methodName);
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @param logLevel one of the predefined levels INFO, WARNING, ERROR, FATAL and SEVERE
   * @param throwable the to be logged throwable
   * @param clazz the originating class
   * @param methodName the name of the relevant method
   */
  @Override
  public void logException(LogLevel logLevel, Throwable throwable, Class clazz, String methodName) {
    this.tracer.logException(logLevel, throwable, clazz, methodName);
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   * @return the thread map of the wrapped tracer
   */
  @Override
  protected AbstractThreadMap getThreadMap() {
    return this.tracer.getThreadMap();
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer. Besides it checks if the
   * stack size of the current tracing context has decreased to zero. If so then the current tracing context
   * will be cleared.
   *
   * @return the TraceMethod which has been popped from the stack - a mere data object for internal use primarily. May be null.
   */
  @Override
  public TraceMethod wayout() {
    TraceMethod traceMethod = this.tracer.wayout();
    if (getThreadMap().getCurrentStackSize() == 0) {
      clearCurrentTracingContext();
      if (!TracerFactory.getInstance().offerTracer(this))
        System.err.printf("WARNING: Offer failed. Possible queue corruption.%n");
    }
    return traceMethod;
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   *
   * @return an {@link IndentablePrintStream}
   */
  @Override
  public IndentablePrintStream out() {
    return this.tracer.out();
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   * @param level the level of the to be printed data
   * @return an {@link IndentablePrintStream}
   */
  @Override
  protected IndentablePrintStream out(int level) {
    return this.tracer.out(level);
  }

  /**
   * Delegates to the corresponding method of the wrapped tracer.
   */
  @Override
  public void clearCurrentTracingContext() {
    this.tracer.clearCurrentTracingContext();
  }
}


text:
/**
 * @author Igor Polevoy: 12/31/13 1:09 PM
 */

package org.javalite.db_migrator.mock;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MockStatement implements Statement {

    protected List<String> executedStatements =  new ArrayList<String>();

    public List<String> getExecutedStatements() {
        return executedStatements;
    }

    public ResultSet executeQuery(String sql) throws SQLException {
        executedStatements.add(sql);
        return null;
    }

    public int executeUpdate(String sql) throws SQLException {
        executedStatements.add(sql);
        return 0;
    }

    public void close() throws SQLException {

    }

    public int getMaxFieldSize() throws SQLException {
        return 0;
    }

    public void setMaxFieldSize(int max) throws SQLException {

    }

    public int getMaxRows() throws SQLException {
        return 0;
    }

    public void setMaxRows(int max) throws SQLException {

    }

    public void setEscapeProcessing(boolean enable) throws SQLException {

    }

    public int getQueryTimeout() throws SQLException {
        return 0;
    }

    public void setQueryTimeout(int seconds) throws SQLException {

    }

    public void cancel() throws SQLException {

    }

    public SQLWarning getWarnings() throws SQLException {
        return null;
    }

    public void clearWarnings() throws SQLException {

    }

    public void setCursorName(String name) throws SQLException {

    }

    public boolean execute(String sql) throws SQLException {
        executedStatements.add(sql);
        return false;
    }

    public ResultSet getResultSet() throws SQLException {
        return null;
    }

    public int getUpdateCount() throws SQLException {
        return 0;
    }

    public boolean getMoreResults() throws SQLException {
        return false;
    }

    public void setFetchDirection(int direction) throws SQLException {

    }

    public int getFetchDirection() throws SQLException {
        return 0;
    }

    public void setFetchSize(int rows) throws SQLException {

    }

    public int getFetchSize() throws SQLException {
        return 0;
    }

    public int getResultSetConcurrency() throws SQLException {
        return 0;
    }

    public int getResultSetType() throws SQLException {
        return 0;
    }

    public void addBatch(String sql) throws SQLException {

    }

    public void clearBatch() throws SQLException {

    }

    public int[] executeBatch() throws SQLException {
        return new int[0];
    }

    public Connection getConnection() throws SQLException {
        return null;
    }

    public boolean getMoreResults(int current) throws SQLException {
        return false;
    }

    public ResultSet getGeneratedKeys() throws SQLException {
        return null;
    }

    public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
        executedStatements.add(sql);
        return 0;
    }

    public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
        executedStatements.add(sql);
        return 0;
    }

    public int executeUpdate(String sql, String[] columnNames) throws SQLException {
        executedStatements.add(sql);
        return 0;
    }

    public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
        executedStatements.add(sql);
        return false;
    }

    public boolean execute(String sql, int[] columnIndexes) throws SQLException {
        executedStatements.add(sql);
        return false;
    }

    public boolean execute(String sql, String[] columnNames) throws SQLException {
        executedStatements.add(sql);
        return false;
    }

    public int getResultSetHoldability() throws SQLException {
        return 0;
    }

    public boolean isClosed() throws SQLException {
        return false;
    }

    public void setPoolable(boolean poolable) throws SQLException {

    }

    public boolean isPoolable() throws SQLException {
        return false;
    }

    public void closeOnCompletion() throws SQLException {

    }

    public boolean isCloseOnCompletion() throws SQLException {
        return false;
    }

    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>The GNU C Library: Permission Bits</title>

<meta name="description" content="The GNU C Library: Permission Bits">
<meta name="keywords" content="The GNU C Library: Permission Bits">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="File-Attributes.html#File-Attributes" rel="up" title="File Attributes">
<link href="Access-Permission.html#Access-Permission" rel="next" title="Access Permission">
<link href="File-Owner.html#File-Owner" rel="prev" title="File Owner">

Next: Access Permission, Previous: File Owner, Up: File Attributes   [Contents][Index]

14.9.5 The Mode Bits for Access Permission

The file mode, stored in the st_mode field of the file
attributes, contains two kinds of information: the file type code, and
the access permission bits.  This section discusses only the access
permission bits, which control who can read or write the file.
See Testing File Type, for information about the file type code.

All of the symbols listed in this section are defined in the header file
<samp>sys/stat.h</samp>.

These symbolic constants are defined for the file mode bits that control
access permission for the file:

S_IRUSR

S_IREAD

Read permission bit for the owner of the file.  On many systems this bit
is 0400.  S_IREAD is an obsolete synonym provided for BSD
compatibility.

S_IWUSR

S_IWRITE

Write permission bit for the owner of the file.  Usually 0200.
S_IWRITE is an obsolete synonym provided for BSD compatibility.

S_IXUSR

S_IEXEC

Execute (for ordinary files) or search (for directories) permission bit
for the owner of the file.  Usually 0100.  S_IEXEC is an obsolete
synonym provided for BSD compatibility.

S_IRWXU

This is equivalent to ‘<samp>(S_IRUSR | S_IWUSR | S_IXUSR)</samp>’.

S_IRGRP

Read permission bit for the group owner of the file.  Usually 040.

S_IWGRP

Write permission bit for the group owner of the file.  Usually 020.

S_IXGRP

Execute or search permission bit for the group owner of the file.
Usually 010.

S_IRWXG

This is equivalent to ‘<samp>(S_IRGRP | S_IWGRP | S_IXGRP)</samp>’.

S_IROTH

Read permission bit for other users.  Usually 04.

S_IWOTH

Write permission bit for other users.  Usually 02.

S_IXOTH

Execute or search permission bit for other users.  Usually 01.

S_IRWXO

This is equivalent to ‘<samp>(S_IROTH | S_IWOTH | S_IXOTH)</samp>’.

S_ISUID

This is the set-user-ID on execute bit, usually 04000.
See How Change Persona.

S_ISGID

This is the set-group-ID on execute bit, usually 02000.
See How Change Persona.

S_ISVTX

This is the sticky bit, usually 01000.

For a directory it gives permission to delete a file in that directory
only if you own that file.  Ordinarily, a user can either delete all the
files in a directory or cannot delete any of them (based on whether the
user has write permission for the directory).  The same restriction
applies—you must have both write permission for the directory and own
the file you want to delete.  The one exception is that the owner of the
directory can delete any file in the directory, no matter who owns it
(provided the owner has given himself write permission for the
directory).  This is commonly used for the <samp>/tmp</samp> directory, where
anyone may create files but not delete files created by other users.

Originally the sticky bit on an executable file modified the swapping
policies of the system.  Normally, when a program terminated, its pages
in core were immediately freed and reused.  If the sticky bit was set on
the executable file, the system kept the pages in core for a while as if
the program were still running.  This was advantageous for a program
likely to be run many times in succession.  This usage is obsolete in
modern systems.  When a program terminates, its pages always remain in
core as long as there is no shortage of memory in the system.  When the
program is next run, its pages will still be in core if no shortage
arose since the last run.

On some modern systems where the sticky bit has no useful meaning for an
executable file, you cannot set the bit at all for a non-directory.
If you try, chmod fails with EFTYPE;
see Setting Permissions.

Some systems (particularly SunOS) have yet another use for the sticky
bit.  If the sticky bit is set on a file that is not executable,
it means the opposite: never cache the pages of this file at all.  The
main use of this is for the files on an NFS server machine which are
used as the swap area of diskless client machines.  The idea is that the
pages of the file will be cached in the client’s memory, so it is a
waste of the server’s memory to cache them a second time.  With this
usage the sticky bit also implies that the filesystem may fail to record
the file’s modification time onto disk reliably (the idea being that
no-one cares for a swap file).

This bit is only available on BSD systems (and those derived from
them).  Therefore one has to use the _GNU_SOURCE feature select
macro, or not define any feature test macros, to get the definition
(see Feature Test Macros).

The actual bit values of the symbols are listed in the table above
so you can decode file mode values when debugging your programs.
These bit values are correct for most systems, but they are not
guaranteed.

Warning: Writing explicit numbers for file permissions is bad
practice.  Not only is it not portable, it also requires everyone who
reads your program to remember what the bits mean.  To make your program
clean use the symbolic names.

Next: Access Permission, Previous: File Owner, Up: File Attributes   [Contents][Index]


text:
#include <cassert>
#include <iostream>

#include <QApplication>
#include <QFileIconProvider>
#include <QFileInfo>
#include <QSet>
#include <QString>
#include <QStyle>
#include <QUrl>
#include <QVariant>

#include <libtransmission/transmission.h>
#include <libtransmission/bencode.h>
#include <libtransmission/utils.h> /* tr_new0, tr_strdup */

#include "app.h"
#include "prefs.h"
#include "torrent.h"
#include "utils.h"

Torrent :: Torrent( Prefs& prefs, int id ):
    magnetTorrent( false ),
    myPrefs( prefs )
{
    for( int i=0; i<PROPERTY_COUNT; ++i )
        assert( myProperties[i].id == i );

    setInt( ID, id );
    setIcon( MIME_ICON, QApplication::style()->standardIcon( QStyle::SP_FileIcon ) );
}

Torrent :: ~Torrent( )
{
}

/***
****
***/

Torrent :: Property
Torrent :: myProperties[] =
{
    { ID, "id", QVariant::Int, INFO, },
    { UPLOAD_SPEED, "rateUpload", QVariant::ULongLong, STAT } /* Bps */,
    { DOWNLOAD_SPEED, "rateDownload", QVariant::ULongLong, STAT }, /* Bps */
    { DOWNLOAD_DIR, "downloadDir", QVariant::String, STAT },
    { ACTIVITY, "status", QVariant::Int, STAT },
    { NAME, "name", QVariant::String, INFO },
    { ERROR, "error", QVariant::Int, STAT },
    { ERROR_STRING, "errorString", QVariant::String, STAT },
    { SIZE_WHEN_DONE, "sizeWhenDone", QVariant::ULongLong, STAT },
    { LEFT_UNTIL_DONE, "leftUntilDone", QVariant::ULongLong, STAT },
    { HAVE_UNCHECKED, "haveUnchecked", QVariant::ULongLong, STAT },
    { HAVE_VERIFIED, "haveValid", QVariant::ULongLong, STAT },
    { DESIRED_AVAILABLE, "desiredAvailable", QVariant::ULongLong, STAT },
    { TOTAL_SIZE, "totalSize", QVariant::ULongLong, INFO },
    { PIECE_SIZE, "pieceSize", QVariant::ULongLong, INFO },
    { PIECE_COUNT, "pieceCount", QVariant::Int, INFO },
    { PEERS_GETTING_FROM_US, "peersGettingFromUs", QVariant::Int, STAT },
    { PEERS_SENDING_TO_US, "peersSendingToUs", QVariant::Int, STAT },
    { WEBSEEDS_SENDING_TO_US, "webseedsSendingToUs", QVariant::Int, STAT_EXTRA },
    { PERCENT_DONE, "percentDone", QVariant::Double, STAT },
    { METADATA_PERCENT_DONE, "metadataPercentComplete", QVariant::Double, STAT },
    { PERCENT_VERIFIED, "recheckProgress", QVariant::Double, STAT },
    { DATE_ACTIVITY, "activityDate", QVariant::DateTime, STAT_EXTRA },
    { DATE_ADDED, "addedDate", QVariant::DateTime, INFO },
    { DATE_STARTED, "startDate", QVariant::DateTime, STAT_EXTRA },
    { DATE_CREATED, "dateCreated", QVariant::DateTime, INFO },
    { PEERS_CONNECTED, "peersConnected", QVariant::Int, STAT },
    { ETA, "eta", QVariant::Int, STAT },
    { RATIO, "uploadRatio", QVariant::Double, STAT },
    { DOWNLOADED_EVER, "downloadedEver", QVariant::ULongLong, STAT },
    { UPLOADED_EVER, "uploadedEver", QVariant::ULongLong, STAT },
    { FAILED_EVER, "corruptEver", QVariant::ULongLong, STAT_EXTRA },
    { TRACKERS, "trackers", QVariant::StringList, STAT },
    { TRACKERSTATS, "trackerStats", TrTypes::TrackerStatsList, STAT_EXTRA },
    { MIME_ICON, "ccc", QVariant::Icon, DERIVED },
    { SEED_RATIO_LIMIT, "seedRatioLimit", QVariant::Double, STAT },
    { SEED_RATIO_MODE, "seedRatioMode", QVariant::Int, STAT },
    { SEED_IDLE_LIMIT, "seedIdleLimit", QVariant::Int, STAT_EXTRA },
    { SEED_IDLE_MODE, "seedIdleMode", QVariant::Int, STAT_EXTRA },
    { DOWN_LIMIT, "downloadLimit", QVariant::Int, STAT_EXTRA }, /* KB/s */
    { DOWN_LIMITED, "downloadLimited", QVariant::Bool, STAT_EXTRA },
    { UP_LIMIT, "uploadLimit", QVariant::Int, STAT_EXTRA }, /* KB/s */
    { UP_LIMITED, "uploadLimited", QVariant::Bool, STAT_EXTRA },
    { HONORS_SESSION_LIMITS, "honorsSessionLimits", QVariant::Bool, STAT_EXTRA },
    { PEER_LIMIT, "peer-limit", QVariant::Int, STAT_EXTRA },
    { HASH_STRING, "hashString", QVariant::String, INFO },
    { IS_FINISHED, "isFinished", QVariant::Bool, STAT },
    { IS_PRIVATE, "isPrivate", QVariant::Bool, INFO },
    { IS_STALLED, "isStalled", QVariant::Bool, STAT },
    { COMMENT, "comment", QVariant::String, INFO },
    { CREATOR, "creator", QVariant::String, INFO },
    { MANUAL_ANNOUNCE_TIME, "manualAnnounceTime", QVariant::DateTime, STAT_EXTRA },
    { PEERS, "peers", TrTypes::PeerList, STAT_EXTRA },
    { TORRENT_FILE, "torrentFile", QVariant::String, STAT_EXTRA },
    { BANDWIDTH_PRIORITY, "bandwidthPriority", QVariant::Int, STAT_EXTRA },
    { QUEUE_POSITION, "queuePosition", QVariant::Int, STAT },
};

Torrent :: KeyList
Torrent :: buildKeyList( Group group )
{
    KeyList keys;

    if( keys.empty( ) )
        for( int i=0; i<PROPERTY_COUNT; ++i )
            if( myProperties[i].id==ID || myProperties[i].group==group )
                keys << myProperties[i].key;

    return keys;
}

const Torrent :: KeyList&
Torrent :: getInfoKeys( )
{
    static KeyList keys;
    if( keys.isEmpty( ) )
        keys << buildKeyList( INFO ) << "files";
    return keys;
}

const Torrent :: KeyList&
Torrent :: getStatKeys( )
{
    static KeyList keys( buildKeyList( STAT ) );
    return keys;
}

const Torrent :: KeyList&
Torrent :: getExtraStatKeys( )
{
    static KeyList keys;
    if( keys.isEmpty( ) )
        keys << buildKeyList( STAT_EXTRA ) << "fileStats";
    return keys;
}

bool
Torrent :: setInt( int i, int value )
{
    bool changed = false;

    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::Int );

    if( myValues[i].isNull() || myValues[i].toInt()!=value )
    {
        myValues[i].setValue( value );
        changed = true;
    }

    return changed;
}

bool
Torrent :: setBool( int i, bool value )
{
    bool changed = false;

    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::Bool );

    if( myValues[i].isNull() || myValues[i].toBool()!=value )
    {
        myValues[i].setValue( value );
        changed = true;
    }

    return changed;
}

bool
Torrent :: setDouble( int i, double value )
{
    bool changed = false;

    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::Double );

    if( myValues[i].isNull() || myValues[i].toDouble()!=value )
    {
        myValues[i].setValue( value );
        changed = true;
    }

    return changed;
}

bool
Torrent :: setDateTime( int i, const QDateTime& value )
{
    bool changed = false;

    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::DateTime );

    if( myValues[i].isNull() || myValues[i].toDateTime()!=value )
    {
        myValues[i].setValue( value );
        changed = true;
    }

    return changed;
}

bool
Torrent :: setSize( int i, qulonglong value )
{
    bool changed = false;

    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::ULongLong );

    if( myValues[i].isNull() || myValues[i].toULongLong()!=value )
    {
        myValues[i].setValue( value );
        changed = true;
    }

    return changed;
}

bool
Torrent :: setString( int i, const char * value )
{
    bool changed = false;

    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::String );

    if( myValues[i].isNull() || myValues[i].toString()!=value )
    {
        myValues[i].setValue( QString::fromUtf8( value ) );
        changed = true;
    }

    return changed;
}

bool
Torrent :: setIcon( int i, const QIcon& value )
{
    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::Icon );

    myValues[i].setValue( value );
    return true;
}

int
Torrent :: getInt( int i ) const
{
    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::Int );

    return myValues[i].toInt( );
}

QDateTime
Torrent :: getDateTime( int i ) const
{
    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::DateTime );

    return myValues[i].toDateTime( );
}

bool
Torrent :: getBool( int i ) const
{
    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::Bool );

    return myValues[i].toBool( );
}

qulonglong
Torrent :: getSize( int i ) const
{
    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::ULongLong );

    return myValues[i].toULongLong( );
}
double
Torrent :: getDouble( int i ) const
{
    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::Double );

    return myValues[i].toDouble( );
}
QString
Torrent :: getString( int i ) const
{
    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::String );

    return myValues[i].toString( );
}
QIcon
Torrent :: getIcon( int i ) const
{
    assert( 0<=i && i<PROPERTY_COUNT );
    assert( myProperties[i].type == QVariant::Icon );

    return myValues[i].value<QIcon>();
}

/***
****
***/

bool
Torrent :: getSeedRatio( double& ratio ) const
{
    bool isLimited;

    switch( seedRatioMode( ) )
    {
        case TR_RATIOLIMIT_SINGLE:
            isLimited = true;
            ratio = seedRatioLimit( );
            break;

        case TR_RATIOLIMIT_GLOBAL:
            if(( isLimited = myPrefs.getBool( Prefs :: RATIO_ENABLED )))
                ratio = myPrefs.getDouble( Prefs :: RATIO );
            break;

        default: // TR_RATIOLIMIT_UNLIMITED:
            isLimited = false;
            break;
    }

    return isLimited;
}

bool
Torrent :: hasFileSubstring( const QString& substr ) const
{
    foreach( const TrFile file, myFiles )
        if( file.filename.contains( substr, Qt::CaseInsensitive ) )
            return true;
    return false;
}

bool
Torrent :: hasTrackerSubstring( const QString& substr ) const
{
    foreach( QString s, myValues[TRACKERS].toStringList() )
        if( s.contains( substr, Qt::CaseInsensitive ) )
            return true;
    return false;
}

int
Torrent :: compareSeedRatio( const Torrent& that ) const
{
    double a;
    double b;
    const bool has_a = getSeedRatio( a );
    const bool has_b = that.getSeedRatio( b );
    if( !has_a && !has_b ) return 0;
    if( !has_a || !has_b ) return has_a ? -1 : 1;
    if( a < b ) return -1;
    if( a > b ) return 1;
    return 0;
}

int
Torrent :: compareRatio( const Torrent& that ) const
{
    const double a = ratio( );
    const double b = that.ratio( );
    if( (int)a == TR_RATIO_INF && (int)b == TR_RATIO_INF ) return 0;
    if( (int)a == TR_RATIO_INF ) return 1;
    if( (int)b == TR_RATIO_INF ) return -1;
    if( a < b ) return -1;
    if( a > b ) return 1;
    return 0;
}

int
Torrent :: compareETA( const Torrent& that ) const
{
    const bool haveA( hasETA( ) );
    const bool haveB( that.hasETA( ) );
    if( haveA && haveB ) return getETA() - that.getETA();
    if( haveA ) return 1;
    if( haveB ) return -1;
    return 0;
}

int
Torrent :: compareTracker( const Torrent& that ) const
{
    Q_UNUSED( that );

    // FIXME
    return 0;
}

/***
****
***/

void
Torrent :: updateMimeIcon( )
{
    const FileList& files( myFiles );

    QIcon icon;

    if( files.size( ) > 1 )
        icon = QFileIconProvider().icon( QFileIconProvider::Folder );
    else if( files.size( ) == 1 )
        icon = Utils :: guessMimeIcon( files.at(0).filename );
    else
        icon = QIcon( );

    setIcon( MIME_ICON, icon );
}

/***
****
***/

void
Torrent :: notifyComplete( ) const
{
    // if someone wants to implement notification, here's the hook.
}

/***
****
***/

void
Torrent :: update( tr_benc * d )
{
    bool changed = false;
    const bool was_seed = isSeed( );
    const uint64_t old_verified_size = haveVerified( );

    for( int  i=0; i<PROPERTY_COUNT; ++i )
    {
        tr_benc * child = tr_bencDictFind( d, myProperties[i].key );
        if( !child )
            continue;

        switch( myProperties[i].type )
        {
            case QVariant :: Int: {
                int64_t val;
                if( tr_bencGetInt( child, &val ) )
                    changed |= setInt( i, val );
                break;
            }

            case QVariant :: Bool: {
                bool val;
                if( tr_bencGetBool( child, &val ) )
                    changed |= setBool( i, val );
                break;
            }

            case QVariant :: String: {
                const char * val;
                if( tr_bencGetStr( child, &val ) )
                    changed |= setString( i, val );
                break;
            }

            case QVariant :: ULongLong: {
                int64_t val;
                if( tr_bencGetInt( child, &val ) )
                    changed |= setSize( i, val );
                break;
            }

            case QVariant :: Double: {
                double val;
                if( tr_bencGetReal( child, &val ) )
                    changed |= setDouble( i, val );
                break;
            }

            case QVariant :: DateTime: {
                int64_t val;
                if( tr_bencGetInt( child, &val ) && val )
                    changed |= setDateTime( i, QDateTime :: fromTime_t( val ) );
                break;
            }

            case QVariant :: StringList:
            case TrTypes :: PeerList:
                break;

            default:
                assert( 0 && "unhandled type" );
        }
    }

    tr_benc * files;

    if( tr_bencDictFindList( d, "files", &files ) ) {
        const char * str;
        int64_t intVal;
        int i = 0;
        myFiles.clear( );
        tr_benc * child;
        while(( child = tr_bencListChild( files, i ))) {
            TrFile file;
            file.index = i++;
            if( tr_bencDictFindStr( child, "name", &str ) )
                file.filename = QString::fromUtf8( str );
            if( tr_bencDictFindInt( child, "length", &intVal ) )
                file.size = intVal;
            myFiles.append( file );
        }
        updateMimeIcon( );
        changed = true;
    }

    if( tr_bencDictFindList( d, "fileStats", &files ) ) {
        const int n = tr_bencListSize( files );
        for( int i=0; i<n && i<myFiles.size(); ++i ) {
            int64_t intVal;
            bool boolVal;
            tr_benc * child = tr_bencListChild( files, i );
            TrFile& file( myFiles[i] );
            if( tr_bencDictFindInt( child, "bytesCompleted", &intVal ) )
                file.have = intVal;
            if( tr_bencDictFindBool( child, "wanted", &boolVal ) )
                file.wanted = boolVal;
            if( tr_bencDictFindInt( child, "priority", &intVal ) )
                file.priority = intVal;
        }
        changed = true;
    }

    tr_benc * trackers;
    if( tr_bencDictFindList( d, "trackers", &trackers ) ) {
        const char * str;
        int i = 0;
        QStringList list;
        tr_benc * child;
        while(( child = tr_bencListChild( trackers, i++ ))) {
            if( tr_bencDictFindStr( child, "announce", &str )) {
                dynamic_cast<MyApp*>(QApplication::instance())->favicons.add( QUrl(QString::fromUtf8(str)) );
                list.append( QString::fromUtf8( str ) );
            }
        }
        if( myValues[TRACKERS] != list ) {
            myValues[TRACKERS].setValue( list );
            changed = true;
        }
    }

    tr_benc * trackerStats;
    if( tr_bencDictFindList( d, "trackerStats", &trackerStats ) ) {
        tr_benc * child;
        TrackerStatsList  trackerStatsList;
        int childNum = 0;
        while(( child = tr_bencListChild( trackerStats, childNum++ ))) {
            bool b;
            int64_t i;
            const char * str;
            TrackerStat trackerStat;
            if( tr_bencDictFindStr( child, "announce", &str ) ) {
                trackerStat.announce = QString::fromUtf8( str );
                dynamic_cast<MyApp*>(QApplication::instance())->favicons.add( QUrl( trackerStat.announce ) );
            }
            if( tr_bencDictFindInt( child, "announceState", &i ) )
                trackerStat.announceState = i;
            if( tr_bencDictFindInt( child, "downloadCount", &i ) )
                trackerStat.downloadCount = i;
            if( tr_bencDictFindBool( child, "hasAnnounced", &b ) )
                trackerStat.hasAnnounced = b;
            if( tr_bencDictFindBool( child, "hasScraped", &b ) )
                trackerStat.hasScraped = b;
            if( tr_bencDictFindStr( child, "host", &str ) )
                trackerStat.host = QString::fromUtf8( str );
            if( tr_bencDictFindInt( child, "id", &i ) )
                trackerStat.id = i;
            if( tr_bencDictFindBool( child, "isBackup", &b ) )
                trackerStat.isBackup = b;
            if( tr_bencDictFindInt( child, "lastAnnouncePeerCount", &i ) )
                trackerStat.lastAnnouncePeerCount = i;
            if( tr_bencDictFindStr( child, "lastAnnounceResult", &str ) )
                trackerStat.lastAnnounceResult = QString::fromUtf8(str);
            if( tr_bencDictFindInt( child, "lastAnnounceStartTime", &i ) )
                trackerStat.lastAnnounceStartTime = i;
            if( tr_bencDictFindBool( child, "lastAnnounceSucceeded", &b ) )
                trackerStat.lastAnnounceSucceeded = b;
            if( tr_bencDictFindInt( child, "lastAnnounceTime", &i ) )
                trackerStat.lastAnnounceTime = i;
            if( tr_bencDictFindBool( child, "lastAnnounceTimedOut", &b ) )
                trackerStat.lastAnnounceTimedOut = b;
            if( tr_bencDictFindStr( child, "lastScrapeResult", &str ) )
                trackerStat.lastScrapeResult = QString::fromUtf8( str );
            if( tr_bencDictFindInt( child, "lastScrapeStartTime", &i ) )
                trackerStat.lastScrapeStartTime = i;
            if( tr_bencDictFindBool( child, "lastScrapeSucceeded", &b ) )
                trackerStat.lastScrapeSucceeded = b;
            if( tr_bencDictFindInt( child, "lastScrapeTime", &i ) )
                trackerStat.lastScrapeTime = i;
            if( tr_bencDictFindBool( child, "lastScrapeTimedOut", &b ) )
                trackerStat.lastScrapeTimedOut = b;
            if( tr_bencDictFindInt( child, "leecherCount", &i ) )
                trackerStat.leecherCount = i;
            if( tr_bencDictFindInt( child, "nextAnnounceTime", &i ) )
                trackerStat.nextAnnounceTime = i;
            if( tr_bencDictFindInt( child, "nextScrapeTime", &i ) )
                trackerStat.nextScrapeTime = i;
            if( tr_bencDictFindInt( child, "scrapeState", &i ) )
                trackerStat.scrapeState = i;
            if( tr_bencDictFindInt( child, "seederCount", &i ) )
                trackerStat.seederCount = i;
            if( tr_bencDictFindInt( child, "tier", &i ) )
                trackerStat.tier = i;
            trackerStatsList << trackerStat;
        }
        myValues[TRACKERSTATS].setValue( trackerStatsList );
        changed = true;
    }

    tr_benc * peers;
    if( tr_bencDictFindList( d, "peers", &peers ) ) {
        tr_benc * child;
        PeerList peerList;
        int childNum = 0;
        while(( child = tr_bencListChild( peers, childNum++ ))) {
            double d;
            bool b;
            int64_t i;
            const char * str;
            Peer peer;
            if( tr_bencDictFindStr( child, "address", &str ) )
                peer.address = QString::fromUtf8( str );
            if( tr_bencDictFindStr( child, "clientName", &str ) )
                peer.clientName = QString::fromUtf8( str );
            if( tr_bencDictFindBool( child, "clientIsChoked", &b ) )
                peer.clientIsChoked = b;
            if( tr_bencDictFindBool( child, "clientIsInterested", &b ) )
                peer.clientIsInterested = b;
            if( tr_bencDictFindStr( child, "flagStr", &str ) )
                peer.flagStr = QString::fromUtf8( str );
            if( tr_bencDictFindBool( child, "isDownloadingFrom", &b ) )
                peer.isDownloadingFrom = b;
            if( tr_bencDictFindBool( child, "isEncrypted", &b ) )
                peer.isEncrypted = b;
            if( tr_bencDictFindBool( child, "isIncoming", &b ) )
                peer.isIncoming = b;
            if( tr_bencDictFindBool( child, "isUploadingTo", &b ) )
                peer.isUploadingTo = b;
            if( tr_bencDictFindBool( child, "peerIsChoked", &b ) )
                peer.peerIsChoked = b;
            if( tr_bencDictFindBool( child, "peerIsInterested", &b ) )
                peer.peerIsInterested = b;
            if( tr_bencDictFindInt( child, "port", &i ) )
                peer.port = i;
            if( tr_bencDictFindReal( child, "progress", &d ) )
                peer.progress = d;
            if( tr_bencDictFindInt( child, "rateToClient", &i ) )
                peer.rateToClient = Speed::fromBps( i );
            if( tr_bencDictFindInt( child, "rateToPeer", &i ) )
                peer.rateToPeer = Speed::fromBps( i );
            peerList << peer;
        }
        myValues[PEERS].setValue( peerList );
        changed = true;
    }

    if( changed )
        emit torrentChanged( id( ) );

    if( !was_seed && isSeed() && (old_verified_size>0) )
        emit torrentCompleted( id( ) );
}

QString
Torrent :: activityString( ) const
{
    QString str;

    switch( getActivity( ) )
    {
        case TR_STATUS_STOPPED:       str = isFinished() ? tr( "Finished" ): tr( "Paused" ); break;
        case TR_STATUS_CHECK_WAIT:    str = tr( "Queued for verification" ); break;
        case TR_STATUS_CHECK:         str = tr( "Verifying local data" ); break;
        case TR_STATUS_DOWNLOAD_WAIT: str = tr( "Queued for download" ); break;
        case TR_STATUS_DOWNLOAD:      str = tr( "Downloading" ); break;
        case TR_STATUS_SEED_WAIT:     str = tr( "Queued for seeding" ); break;
        case TR_STATUS_SEED:          str = tr( "Seeding" ); break;
    }

    return str;
}

QString
Torrent :: getError( ) const
{
    QString s = getString( ERROR_STRING );

    switch( getInt( ERROR ) )
    {
        case TR_STAT_TRACKER_WARNING: s = tr( "Tracker gave a warning: %1" ).arg( s ); break;
        case TR_STAT_TRACKER_ERROR: s = tr( "Tracker gave an error: %1" ).arg( s ); break;
        case TR_STAT_LOCAL_ERROR: s = tr( "Error: %1" ).arg( s ); break;
        default: s.clear(); break;
    }

    return s;
}

QPixmap
TrackerStat :: getFavicon( ) const
{
    MyApp * myApp = dynamic_cast<MyApp*>(QApplication::instance());
    return myApp->favicons.find( QUrl( announce ) );
}


text:
date: 2020-05-03T13:05:57-0600
updated: 2020-05-03T13:13:00-0600
feedId: /notes/1305/
tags:
    - Zettelkasten
    - note-taking

---

I got curious, and (after some [command-line shenanigans]) figured out that I've written/collected about 22,000 words of notes in my [Zettelkasten] so far in 2020. That's… a lot of notes. 😅

[command-line shenanigans]: https://v5.chriskrycho.com/journal/find-grep-xargs-newlines-null/
[Zettelkasten]: https://v5.chriskrycho.com/topics/zettelkasten/