text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 3.0.7
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */
package com.ctp.field;

import com.ctp.swig.ctpJNI;

public class CThostFtdcQryInstrumentTradingRightField
{
	private transient long swigCPtr;
	protected transient boolean swigCMemOwn;

	protected CThostFtdcQryInstrumentTradingRightField(long cPtr, boolean cMemoryOwn)
	{
		swigCMemOwn = cMemoryOwn;
		swigCPtr = cPtr;
	}

	public static long getCPtr(CThostFtdcQryInstrumentTradingRightField obj)
	{
		return (obj == null) ? 0 : obj.swigCPtr;
	}

	protected void finalize()
	{
		delete();
	}

	public synchronized void delete()
	{
		if (swigCPtr != 0)
		{
			if (swigCMemOwn)
			{
				swigCMemOwn = false;
				ctpJNI.delete_CThostFtdcQryInstrumentTradingRightField(swigCPtr);
			}
			swigCPtr = 0;
		}
	}

	public void setBrokerID(String value)
	{
		ctpJNI.CThostFtdcQryInstrumentTradingRightField_BrokerID_set(swigCPtr, this, value);
	}

	public String getBrokerID()
	{
		return ctpJNI.CThostFtdcQryInstrumentTradingRightField_BrokerID_get(swigCPtr, this);
	}

	public void setInvestorID(String value)
	{
		ctpJNI.CThostFtdcQryInstrumentTradingRightField_InvestorID_set(swigCPtr, this, value);
	}

	public String getInvestorID()
	{
		return ctpJNI.CThostFtdcQryInstrumentTradingRightField_InvestorID_get(swigCPtr, this);
	}

	public void setInstrumentID(String value)
	{
		ctpJNI.CThostFtdcQryInstrumentTradingRightField_InstrumentID_set(swigCPtr, this, value);
	}

	public String getInstrumentID()
	{
		return ctpJNI.CThostFtdcQryInstrumentTradingRightField_InstrumentID_get(swigCPtr, this);
	}

	public CThostFtdcQryInstrumentTradingRightField()
	{
		this(ctpJNI.new_CThostFtdcQryInstrumentTradingRightField(), true);
	}
}

redpajama_set_name: RedPajamaGithub


text:
from django.utils.importlib import import_module
from django.conf import settings

def get_aggregate_data(starttime):
    ds_module = getattr(settings, 'STATUS_APP_DATASOURCE', 'status_app.datasource.memory')
    mod = import_module(ds_module)

    return mod.get_aggregate_data(starttime)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System;
using System.Collections.Generic;
using System.Text.Json.Serialization;
#if EXPERIMENTAL_SPATIAL
using Azure.Core.Spatial;
#else
using Microsoft.Spatial;
#endif
using KeyFieldAttribute = System.ComponentModel.DataAnnotations.KeyAttribute;

#pragma warning disable SA1402 // File may only contain a single type
#pragma warning disable SA1649 // File name should match first type name

// TODO: Remove when https://github.com/Azure/azure-sdk-for-net/issues/11166 is completed.
namespace Azure.Search.Documents.Samples.Tests
{
    public struct ReflectableAddressStruct
    {
        [IsSearchable]
        public string City { get; set; }

        [IsFilterable, IsFacetable]
        public string Country { get; set; }
    }

    public struct ReflectableComplexStruct
    {
        [IsSearchable]
        [Analyzer("en.microsoft")]
        public string Name { get; set; }

        [IsFilterable]
        public int Rating { get; set; }

        // Ensure that leaf-field-specific attributes are ignored by FieldBuilder on complex fields.
        [IsSearchable]
        [IsFilterable]
        [IsSortable]
        [IsFacetable]
        [IsRetrievable(false)]
        [Analyzer("zh-Hant.lucene")]
        [IndexAnalyzer("zh-Hant.lucene")]
        [SearchAnalyzer("zh-Hant.lucene")]
        [SynonymMaps("myMap")]
        public ReflectableAddressStruct Address { get; set; }
    }

    public struct ReflectableStructModel
    {
        [KeyField]
        public int Id { get; set; }

        public long BigNumber { get; set; }

        public double Double { get; set; }

        public bool Flag { get; set; }

        public DateTimeOffset Time { get; set; }

        public DateTime TimeWithoutOffset { get; set; }

        [IsSearchable]
        [SynonymMaps("myMap")]
        public string Text { get; set; }

        public string UnsearchableText { get; set; }

        [IsSearchable]
        public string MoreText { get; set; }

        [IsFilterable]
        public string FilterableText { get; set; }

        [IsSortable]
        public string SortableText { get; set; }

        [IsFacetable]
        public string FacetableText { get; set; }

        [IsRetrievable(false)]
        public string IrretrievableText { get; set; }

        [IsRetrievable(true)]
        public string ExplicitlyRetrievableText { get; set; }

        [Analyzer("en.microsoft")]
        public string TextWithAnalyzer { get; set; }

        [SearchAnalyzer("es.lucene")]
        public string TextWithSearchAnalyzer { get; set; }

        [IndexAnalyzer("whitespace")]
        public string TextWithIndexAnalyzer { get; set; }

        public string[] StringArray { get; set; }

        public IList<string> StringIList { get; set; }

        public List<string> StringList { get; set; }

        public IEnumerable<string> StringIEnumerable { get; set; }

        public ICollection<string> StringICollection { get; set; }

        public int? NullableInt { get; set; }

#if EXPERIMENTAL_SPATIAL
        public PointGeometry GeographyPoint { get; set; }
#else
        public GeographyPoint GeographyPoint { get; set; }
#endif

        public int[] IntArray { get; set; }

        public IList<int> IntIList { get; set; }

        public List<int> IntList { get; set; }

        public IEnumerable<int> IntIEnumerable { get; set; }

        public ICollection<int> IntICollection { get; set; }

        public long[] LongArray { get; set; }

        public IList<long> LongIList { get; set; }

        public List<long> LongList { get; set; }

        public IEnumerable<long> LongIEnumerable { get; set; }

        public ICollection<long> LongICollection { get; set; }

        public double[] DoubleArray { get; set; }

        public IList<double> DoubleIList { get; set; }

        public List<double> DoubleList { get; set; }

        public IEnumerable<double> DoubleIEnumerable { get; set; }

        public ICollection<double> DoubleICollection { get; set; }

        public bool[] BoolArray { get; set; }

        public IList<bool> BoolIList { get; set; }

        public List<bool> BoolList { get; set; }

        public IEnumerable<bool> BoolIEnumerable { get; set; }

        public ICollection<bool> BoolICollection { get; set; }

        public DateTime[] DateTimeArray { get; set; }

        public IList<DateTime> DateTimeIList { get; set; }

        public List<DateTime> DateTimeList { get; set; }

        public IEnumerable<DateTime> DateTimeIEnumerable { get; set; }

        public ICollection<DateTime> DateTimeICollection { get; set; }

        public DateTimeOffset[] DateTimeOffsetArray { get; set; }

        public IList<DateTimeOffset> DateTimeOffsetIList { get; set; }

        public List<DateTimeOffset> DateTimeOffsetList { get; set; }

        public IEnumerable<DateTimeOffset> DateTimeOffsetIEnumerable { get; set; }

        public ICollection<DateTimeOffset> DateTimeOffsetICollection { get; set; }

#if EXPERIMENTAL_SPATIAL
        public PointGeometry[] GeographyPointArray { get; set; }

        public IList<PointGeometry> GeographyPointIList { get; set; }

        public List<PointGeometry> GeographyPointList { get; set; }

        public IEnumerable<PointGeometry> GeographyPointIEnumerable { get; set; }

        public ICollection<PointGeometry> GeographyPointICollection { get; set; }
#else
        public GeographyPoint[] GeographyPointArray { get; set; }

        public IList<GeographyPoint> GeographyPointIList { get; set; }

        public List<GeographyPoint> GeographyPointList { get; set; }

        public IEnumerable<GeographyPoint> GeographyPointIEnumerable { get; set; }

        public ICollection<GeographyPoint> GeographyPointICollection { get; set; }
#endif

        public ReflectableComplexStruct? Complex { get; set; }

        public ReflectableComplexStruct[] ComplexArray { get; set; }

        public IList<ReflectableComplexStruct> ComplexIList { get; set; }

        public List<ReflectableComplexStruct> ComplexList { get; set; }

        public IEnumerable<ReflectableComplexStruct> ComplexIEnumerable { get; set; }

        public ICollection<ReflectableComplexStruct> ComplexICollection { get; set; }

        [JsonIgnore]
        [IsRetrievable(false)]
#pragma warning disable IDE1006 // Naming Styles
        public RecordEnum recordEnum { get; set; }
#pragma warning restore IDE1006 // Naming Styles
    }
}


text:
class Attempt < ApplicationRecord
  belongs_to :user
end


text:
.. automodule:: insights.parsers.postgresql_conf
    :members:
    :show-inheritance:


text:
class TCPTestSuite
{
public:
	static CppUnit::Test* suite();
};

#endif // TCPTestSuite_INCLUDED


text:
package com.atsebak.kernel.project;

import com.atsebak.kernel.project.builder.CppModuleBuilder;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class KernelSupportProjectTemplatesFactoryTest {
    @Test
    public void testAndroidBSPId() {
        CppModuleBuilder.AndroidBSP androidBSP = new CppModuleBuilder.AndroidBSP();
        assertEquals(androidBSP.getBuilderId(), "linux.android.bsp");
    }

    @Test
    public void testDriverId() {
        CppModuleBuilder.Driver driver = new CppModuleBuilder.Driver();
        assertEquals(driver.getBuilderId(), "linux.driver");
    }
}


text:
"use strict";

var socket  = require("socket.io");
var Steward = require("emitter-steward");

/**
 * Plugin interface
 * @returns {*|function(this:exports)}
 */
module.exports.plugin = function (server, clientEvents, bs) {
    return exports.init(server, clientEvents, bs);
};

/**
 * @param {http.Server} server
 * @param clientEvents
 * @param {BrowserSync} bs
 */
module.exports.init = function (server, clientEvents, bs) {

    var emitter  = bs.events;
    var socketConfig = bs.options.get("socket").toJS();

    var io = socket.listen(server, {log: false, path: socketConfig.path});

    // Override default namespace.
    io.sockets = io.of(socketConfig.namespace || "/browser-sync");

    io.set("heartbeat interval", socketConfig.clients.heartbeatTimeout);

    var steward  = new Steward(emitter);

    /**
     * Listen for new connections
     */
    io.sockets.on("connection", handleConnection);

    /**
     * Handle each new connection
     * @param {Object} client
     */
    function handleConnection (client) {

        // set ghostmode callbacks
        if (bs.options.get("ghostMode")) {

            addGhostMode(client);
        }

        client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients

        emitter.emit("client:connected", {
            ua: client.handshake.headers["user-agent"]
        });
    }

    /**
     * @param {string} event
     * @param {Socket.client} client
     * @param {Object} data
     */
    function handleClientEvent(event, client, data) {

        if (steward.valid(client.id)) {

            client.broadcast.emit(event, data);
        }
    }

    /**
     * @param client
     */
    function addGhostMode (client) {

        clientEvents.forEach(addEvent);

        function addEvent(event) {

            client.on(event, handleClientEvent.bind(null, event, client));
        }
    }

    return io;
};


text:
import sbt._
import sbt.Keys._

import com.typesafe.sbt.pgp.PgpKeys._

import sbtrelease._
import sbtrelease.ReleasePlugin._
import sbtrelease.ReleasePlugin.ReleaseKeys._
import sbtrelease.ReleaseStateTransformations._

import xerial.sbt.Sonatype.sonatypeSettings
import xerial.sbt.Sonatype.SonatypeKeys._

object NtParserBuild extends Build {

  lazy val core =
    Project("core", file("core")).settings(ntparserSettings: _*)

  lazy val model =
    Project("model", file("models") / "nt").settings(ntparserSettings: _*)
      .dependsOn(core)

  lazy val jena =
    Project("jena", file("models") / "jena").settings(ntparserSettings: _*)
      .dependsOn(core)

  lazy val examples =
    Project("examples", file("examples")).settings(noPublishSettings: _*)
      .dependsOn(core, model, jena)

  lazy val tests =
    Project("tests", file("tests")).settings(noPublishSettings: _*)
      .dependsOn(core, model, jena)

  lazy val parent =
    Project("parent", file(".")).settings(noPublishSettings: _*)
      .aggregate(core, model, jena, examples, tests)
      .dependsOn(core, model, jena, examples, tests)

  lazy val ntparserSettings = signedReleaseSettings ++ sonatypeSettings

  lazy val noPublishSettings = List(
    publish := (),
    publishLocal := (),
    publishArtifact := false
  )

  lazy val signedReleaseSettings = releaseSettings ++ List(
    releaseProcess := List[ReleaseStep](
      checkSnapshotDependencies,
      inquireVersions,
      setReleaseVersion,
      runClean,
      runTest,
      commitReleaseVersion,
      tagRelease,
      publishSignedArtifacts,
      releaseToCentral,
      setNextVersion,
      commitNextVersion,
      pushChanges,
      publishArtifacts
    ),
    tagComment <<= (Keys.version in ThisBuild) map (v => s"Release version $v"),
    commitMessage <<= (Keys.version in ThisBuild) map (v => s"Set version to $v"),
    versionBump := sbtrelease.Version.Bump.Bugfix
  )

  lazy val publishSignedArtifacts = publishArtifacts.copy(
    action = { st: State =>
      val extracted = Project.extract(st)
      val ref = extracted.get(Keys.thisProjectRef)
      extracted.runAggregated(publishSigned in Global in ref, st)
    },
    enableCrossBuild = true
  )

  lazy val releaseToCentral = ReleaseStep(
    action = { st: State =>
      val extracted = Project.extract(st)
      val ref = extracted.get(Keys.thisProjectRef)
      extracted.runAggregated(sonatypeReleaseAll in Global in ref, st)
    },
    enableCrossBuild = true
  )
}


text:
import { Component, HostBinding, Input, ElementRef, AfterViewInit, ChangeDetectionStrategy } from '@angular/core';

@Component({
  selector: 'header-search',
  template: `
    <nz-input-group [nzAddOnBeforeIcon]="focus ? 'arrow-down' : 'search'">
      <input
        nz-input
        [(ngModel)]="q"
        (focus)="qFocus()"
        (blur)="qBlur()"
        [placeholder]="'menu.search.placeholder' | translate"
      />
    </nz-input-group>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class HeaderSearchComponent implements AfterViewInit {
  q: string;

  qIpt: HTMLInputElement;

  @HostBinding('class.alain-default__search-focus')
  focus = false;

  @HostBinding('class.alain-default__search-toggled')
  searchToggled = false;

  @Input()
  set toggleChange(value: boolean) {
    if (typeof value === 'undefined') return;
    this.searchToggled = true;
    this.focus = true;
    setTimeout(() => this.qIpt.focus(), 300);
  }

  constructor(private el: ElementRef) {}

  ngAfterViewInit() {
    this.qIpt = (this.el.nativeElement as HTMLElement).querySelector('.ant-input') as HTMLInputElement;
  }

  qFocus() {
    this.focus = true;
  }

  qBlur() {
    this.focus = false;
    this.searchToggled = false;
  }
}


text:
package infrastructure_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"

	. "github.com/cloudfoundry/bosh-agent/infrastructure"
	boshlog "github.com/cloudfoundry/bosh-agent/logger"
	fakesys "github.com/cloudfoundry/bosh-agent/system/fakes"
)

var _ = Describe("FileMetadataService", func() {
	var (
		fs              *fakesys.FakeFileSystem
		metadataService MetadataService
	)

	BeforeEach(func() {
		fs = fakesys.NewFakeFileSystem()
		logger := boshlog.NewLogger(boshlog.LevelNone)
		metadataService = NewFileMetadataService(
			"fake-metadata-file-path",
			"fake-userdata-file-path",
			"fake-settings-file-path",
			fs,
			logger,
		)
	})

	Describe("GetInstanceID", func() {
		Context("when metadata service file exists", func() {
			BeforeEach(func() {
				metadataContents := `{"instance-id":"fake-instance-id"}`
				fs.WriteFileString("fake-metadata-file-path", metadataContents)
			})

			It("returns instance id", func() {
				instanceID, err := metadataService.GetInstanceID()
				Expect(err).NotTo(HaveOccurred())
				Expect(instanceID).To(Equal("fake-instance-id"))
			})
		})

		Context("when metadata service file does not exist", func() {
			It("returns an error", func() {
				_, err := metadataService.GetInstanceID()
				Expect(err).To(HaveOccurred())
			})
		})
	})

	Describe("GetRegistryEndpoint", func() {
		Context("when metadata service file exists", func() {
			BeforeEach(func() {
				userDataContents := `{"registry":{"endpoint":"fake-registry-endpoint"}}`
				fs.WriteFileString("fake-userdata-file-path", userDataContents)
			})

			It("returns registry endpoint", func() {
				registryEndpoint, err := metadataService.GetRegistryEndpoint()
				Expect(err).NotTo(HaveOccurred())
				Expect(registryEndpoint).To(Equal("fake-registry-endpoint"))
			})
		})

		Context("when metadata service file does not exist", func() {
			It("returns registry endpoint pointing to a settings file", func() {
				registryEndpoint, err := metadataService.GetRegistryEndpoint()
				Expect(err).NotTo(HaveOccurred())
				Expect(registryEndpoint).To(Equal("fake-settings-file-path"))
			})
		})
	})

	Describe("IsAvailable", func() {
		It("returns true", func() {
			Expect(metadataService.IsAvailable()).To(BeTrue())
		})
	})
})


text:
openerp_announcement = function(instance) {
    instance.web.WebClient.include({
        show_application: function() {
            return $.when(this._super.apply(this, arguments)).then(this.proxy('show_annoucement_bar'));
        },
        _ab_location: function(dbuuid) {
            return _.str.sprintf('mail/static/src/css/announce.css', dbuuid);
        },
        show_annoucement_bar: function() {
            if (this.session.get_cookie('ab') === 'c') {
                return;
            }
            var self = this;
            var config_parameter = new instance.web.Model('ir.config_parameter');
            $(openerp.qweb.render('WebClient.announcement_bar')).prependTo($('body'));
            var $bar = $('#announcement_bar_table');

            return config_parameter.call('get_param', ['database.uuid', false]).then(function(dbuuid) {
                if (!dbuuid) {
                    return;
                }
                var $link = $bar.find('.url a');
                $link.attr('href', _.str.sprintf('%s/%s', $link.attr('href'), dbuuid));
                var $css = $('<link />').attr({
                    rel : 'stylesheet',
                    type: 'text/css',
                    media: 'screen',
                    href: self._ab_location(dbuuid)
                });
                $css.on('load', function() {
                    var close = function() {
                        var ttl = 7*24*60*60;
                        self.session.set_cookie('ab', 'c', ttl);
                        $bar.slideUp();
                        setTimeout(function () {
                            $('.openerp_webclient_container').css('height', 'calc(100% - 34px)');
                        }, 400);
                    };
                    /*
                        We need a timeout of at least 350ms because the announcement bar appears
                        with an animation of 350ms and the computed height might be wrong if we don't wait
                    */
                    setTimeout(function(){
                        var height = $('#announcement_bar_table').outerHeight()
                                    + $('#oe_main_menu_navbar').outerHeight();
                        $('.openerp_webclient_container').css('height', 'calc(100% - ' + height + 'px)');
                        $bar.find('.close').on('click', close);
                        self.trigger('ab_loaded', $bar);
                    }, 400)
                });

                $('head').append($css);
            }).fail(function(result, ev){
                ev.preventDefault();
            });
        }
    });
};


text:
using System;

namespace NUnit.Framework
{
    /// <summary>
    /// FactoryAttribute indicates the source to be used to
    /// provide test cases for a test method.
    /// </summary>
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = false)]
    public class TestCaseSourceAttribute : Attribute
    {
        private readonly string sourceName;
        private readonly Type sourceType;
        private string category;

        /// <summary>
        /// Construct with the name of the factory - for use with languages
        /// that don't support params arrays.
        /// </summary>
        /// <param name="sourceName">An array of the names of the factories that will provide data</param>
        public TestCaseSourceAttribute(string sourceName)
        {
            this.sourceName = sourceName;
        }

        /// <summary>
        /// Construct with a Type and name - for use with languages
        /// that don't support params arrays.
        /// </summary>
        /// <param name="sourceType">The Type that will provide data</param>
        /// <param name="sourceName">The name of the method, property or field that will provide data</param>
        public TestCaseSourceAttribute(Type sourceType, string sourceName)
        {
            this.sourceType = sourceType;
            this.sourceName = sourceName;
        }

        /// <summary>
        /// The name of a the method, property or fiend to be used as a source
        /// </summary>
        public string SourceName
        {
            get { return sourceName; }
        }

        /// <summary>
        /// A Type to be used as a source
        /// </summary>
        public Type SourceType
        {
            get { return sourceType;  }
        }

        /// <summary>
        /// Gets or sets the category associated with this test.
        /// May be a single category or a comma-separated list.
        /// </summary>
        public string Category
        {
            get { return category; }
            set { category = value; }
        }
    }
}


text:
package kikaha.uworkers.api;

import java.lang.annotation.*;

/**
 *
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
public @interface Worker {

	/**
	 * Defines the value name this Worker is listen for messages.
	 * @return
	 */
	String value();

	/**
	 * Defines if should use the "listener name" as external HTTP URI.
	 * Otherwise, the uWorkersAPI will try to create one external HTTP URI automatically.
	 * By default, it uses the Canonical Name of method annotated with @Worker annotation.
	 * For example, the following class will be exposed at "/{base-endpoint}/sample.MyWorkerClass.method".
	 * The "base-endpoint" will be replaced by the value defined at the
	 * "{@code server.uworkers.rest-api.base-endpoint}" entry of the configuration file.

	 *
	 *

	 * package sample;
	 * import kikaha.uworkers.api.Worker.
	 *
	 * class MyWorkerClass {
	 *    {@code @Worker("name")}
	 *     void method( Exchange exchange ){
	 *         exchange.reply("OK");
	 *     }
	 * }
	 *

	 *
	 *
	 *
	 * @return
	 */
	boolean useNameAsHttpURI() default false;
}


text:
NS_ASSUME_NONNULL_BEGIN

@class CardIOProxy, CardIOCardParams;

@protocol CardIOProxyDelegate
- (void)cardIOProxy:(CardIOProxy *)proxy
    didFinishWithCardParams:(CardIOCardParams *)cardParams
    NS_SWIFT_NAME(cardIOProxy(_:didFinishWith:));
- (void)didCancelCardIOProxy:(CardIOProxy *)proxy NS_SWIFT_NAME(didCancel(in:));
@end

@interface CardIOProxy : NSObject

+ (BOOL)isCardIOAvailable;
+ (BOOL)canReadCardWithCamera;
- (instancetype)initWithDelegate:(id<CardIOProxyDelegate>)delegate;
- (void)presentCardIOFromViewController:(UIViewController *)viewController;

@end

NS_ASSUME_NONNULL_END
#endif


text:
using System;
using System.Collections.Generic;

namespace CChessCore
{
    public interface IGameBoard : IEnumerable<Tuple<Square,IPiece>>
    {
        IPiece this[Square s] { get; set; }
        void SetPosition(IPiece[,] position);
        IPiece[,] GetPosition();
        void SetToInitialPosition();
        void ClearBoard();

        event EventHandler<PositionChangedEventArgs> PositionChanged;

        bool IsMutable { get; }
        IGameBoard Copy();
    }
}


text:
#include <QLineEdit>
#include <QCheckBox>
#include <QSlider>
#include <QComboBox>
#include <QPainter>
#include <QApplication>
#include <QSpinBox>
#include <QSignalBlocker>
#include <QCheckBox>

#include "../../model_view/TreeNode.h"
#include "../model/Param.h"
#include "../model/BooleanParam.h"
#include "../model/TextParam.h"
#include "../model/RangeParam.h"
#include "../model/ChoiceParam.h"
#include "GenConfigDelegate.h"

namespace Quartz {

GenConfigDelegate::GenConfigDelegate(QWidget* parent)
    : QStyledItemDelegate(parent) {
}

QWidget* GenConfigDelegate::createEditor(QWidget* parent,
                                         const QStyleOptionViewItem& /*option*/,
                                         const QModelIndex& index) const {
    QWidget* widget = new QLineEdit(parent);
    auto node = index.data(Qt::UserRole).value<TreeNode*>();
    auto param = dynamic_cast<Param*>(node);
    if (param != nullptr) {
        switch (param->type()) {
        case ParamType::Text: {
            auto le = new QLineEdit(parent);
            widget = le;
            connect(le, &QLineEdit::textEdited, [le, this]() {
                // I know, const_cast is bad...
                emit const_cast<GenConfigDelegate*>(this)->commitData(le);
            });
        } break;
        case ParamType::Range: {
            auto sl = new QSpinBox(parent);
            widget = sl;
            connect(sl, &QSpinBox::editingFinished, [sl, this]() {
                // I know, const_cast is bad...
                emit const_cast<GenConfigDelegate*>(this)->commitData(sl);
            });
        } break;
        case ParamType::Choice: {
            auto combo = new QComboBox(parent);
            widget = combo;
            connect(combo,
                    qOverload<int>(&QComboBox::currentIndexChanged),
                    [combo, this]() {
                        // I know, const_cast is bad...
                        emit const_cast<GenConfigDelegate*>(this)->commitData(
                            combo);
                    });
        } break;
        case ParamType::Boolean: {
            auto checkbox = new QCheckBox(parent);
            connect(checkbox, &QCheckBox::stateChanged, [checkbox, this]() {
                // I know, const_cast is bad...
                emit const_cast<GenConfigDelegate*>(this)->commitData(checkbox);
            });
            widget = checkbox;
        } break;
        case ParamType::Fixed: // no edit for fixed
            break;
        }
    }
    return widget;
}

void GenConfigDelegate::setEditorData(QWidget* editor,
                                      const QModelIndex& index) const {
    auto node = treenode_cast<Param*>(index.data(Qt::UserRole));
    if (node != nullptr) {
        switch (node->type()) {
        case ParamType::Boolean: {
            //            QStyledItemDelegate::setEditorData(editor, index);
            auto bparam = static_cast<BooleanParam*>(node);
            auto cb = static_cast<QCheckBox*>(editor);
            cb->setChecked(bparam->value().toBool());
        } break;
        case ParamType::Text: {
            auto tparam = static_cast<TextParam*>(node);
            auto le = static_cast<QLineEdit*>(editor);
            le->setText(tparam->value().toString());
        } break;
        case ParamType::Range: {
            auto rparam = static_cast<RangeParam*>(node);
            auto sl = static_cast<QSpinBox*>(editor);
            sl->setValue(rparam->value().toInt());
        } break;
        case ParamType::Choice: {
            auto cparam = static_cast<ChoiceParam*>(node);
            auto combo = static_cast<QComboBox*>(editor);
            for (auto i = 0; i < cparam->numOption(); ++i) {
                auto opt = cparam->option(i);
                combo->addItem(opt.first, opt.second);
            }
            if (cparam->numOption() > 0) {
                combo->setCurrentIndex(cparam->index());
            }
            //            combo->showPopup();
        } break;
        case ParamType::Fixed: // no edit for fixed
            break;
        }
    }
}

void GenConfigDelegate::setModelData(QWidget* editor,
                                     QAbstractItemModel* model,
                                     const QModelIndex& index) const {
    auto node = treenode_cast<Param*>(index.data(Qt::UserRole));
    if (node != nullptr) {
        QVariant data;
        switch (node->type()) {
        case ParamType::Boolean: {
            auto cb = static_cast<QCheckBox*>(editor);
            data = cb->checkState();
            return; //?
        }
        case ParamType::Text: {
            auto le = static_cast<QLineEdit*>(editor);
            data = le->text();
        } break;
        case ParamType::Range: {
            auto sl = static_cast<QSpinBox*>(editor);
            data = sl->value();
        } break;
        case ParamType::Choice: {
            auto combo = static_cast<QComboBox*>(editor);
            data = combo->currentData();
        } break;
        case ParamType::Fixed: // no edit for fixed
            data = node->value();
            break;
        }
        model->setData(index, data);
    }
}

void GenConfigDelegate::updateEditorGeometry(
    QWidget* editor,
    const QStyleOptionViewItem& option,
    const QModelIndex& /*index*/) const {
    editor->setGeometry(option.rect);
}

} // namespace Quartz


text:
> **Approximate length:** This milestone is intended to last approximately 2 weeks.

![C# Foundations](foundations.png)

## Installs

### .NET Core

[.NET Core](https://www.microsoft.com/net/core) is the most recent version of the platform that we'll be using in class. It now runs on Linux, OSX and Windows, which means that you can be up and running in a matter of minutes. You will learn the basics of the language while you get Windows and the full Visual Studio IDE installed.

### Visual Studio

* [Visual Studio Code](https://code.visualstudio.com) will be your first editor while learning the language. While not as powerful as the full Visual Studio IDE that you will install on Windows, it has **many** of the features and you can build most any moderately complex project with it.

* After you have Windows installed in a VM, or through Parallels, install [Visual Studio Community Edition](https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx) which will be your Windows coding environment while working with C# and .NET.

> **Note:** Did you have snippets in Sublime or Atom? You can [make them](https://code.visualstudio.com/docs/customization/userdefinedsnippets) in Code, too.

### SQL Server

* Visit the [SQL Server Express 2014](https://www.microsoft.com/en-us/download/details.aspx?id=35579) page, click the download button and select the  `SQLEXPR_x64_ENU.exe` and the `
SQLManagementStudio_x64_ENU.exe` which installs the SQL Server Mangement Studio.


text:
				<?= $banner->content;?>

				Previous

				Next

					<?= $article->content ?>


text:
#include "condor_common.h"
#include "condor_config.h"
#include "string_list.h"

#include "condorresource.h"
#include "condorjob.h"
#include "gridmanager.h"

std::map <std::string, CondorResource *>
    CondorResource::ResourcesByName;

HashTable <std::string, CondorResource::ScheddPollInfo *>
    CondorResource::PollInfoByName( hashFunction );

std::string & CondorResource::HashName( const char *resource_name,
                                      const char *pool_name,
                                      const char *proxy_subject,
                                      const std::string &scitokens_file )
{
	static std::string hash_name;

	formatstr( hash_name, "condor %s %s#%s#%s", resource_name,
	           pool_name ? pool_name : "NULL",
	           proxy_subject ? proxy_subject : "NULL",
	           scitokens_file.c_str() );

	return hash_name;
}

CondorResource *CondorResource::FindOrCreateResource( const char * resource_name,
                                                      const char *pool_name,
                                                      const Proxy *proxy,
                                                      const std::string &scitokens_file )
{
	CondorResource *resource = NULL;
	std::string &key = HashName( resource_name, pool_name,
	                             proxy ? proxy->subject->fqan : NULL,
	                             scitokens_file );
	auto itr = ResourcesByName.find( key );
	if ( itr == ResourcesByName.end() ) {
		resource = new CondorResource( resource_name, pool_name,
		                               proxy, scitokens_file );
		ASSERT(resource);
		resource->Reconfig();
		ResourcesByName[key] = resource;
	} else {
		resource = itr->second;
		ASSERT(resource);
	}

	return resource;
}

CondorResource::CondorResource( const char *resource_name, const char *pool_name,
                                const Proxy *proxy, const std::string &scitokens_file )
	: BaseResource( resource_name )
{
	hasLeases = true;

	if ( proxy != NULL ) {
		proxySubject = strdup( proxy->subject->subject_name );
		proxyFQAN = strdup( proxy->subject->fqan );
	} else {
		proxySubject = NULL;
		proxyFQAN = NULL;
	}
	scheddPollTid = TIMER_UNSET;
	scheddName = strdup( resource_name );
	gahp = NULL;
	ping_gahp = NULL;
	scheddStatusActive = false;
	submitter_constraint = "";
	m_scitokensFile = scitokens_file;

	if ( pool_name != NULL ) {
		poolName = strdup( pool_name );
	} else {
		poolName = NULL;
	}

	scheddPollTid = daemonCore->Register_Timer( 0,
							(TimerHandlercpp)&CondorResource::DoScheddPoll,
							"CondorResource::DoScheddPoll", (Service*)this );

	char *gahp_path = param("CONDOR_GAHP");
	if ( gahp_path == NULL ) {
		EXCEPT( "CONDOR_GAHP not defined in condor config file" );
	} else {
		// TODO remove scheddName from the gahp server key if/when
		//   a gahp server can handle multiple schedds
		std::string buff;
		ArgList args;
		formatstr( buff, "CONDOR/%s/%s/%s#%s", poolName ? poolName : "NULL",
		           scheddName, proxyFQAN ? proxyFQAN : "NULL",
		           m_scitokensFile.c_str() );
		args.AppendArg("-f");
		args.AppendArg("-s");
		args.AppendArg(scheddName);
		if ( poolName != NULL ) {
			args.AppendArg("-P");
			args.AppendArg(poolName);
		}

		gahp = new GahpClient( buff.c_str(), gahp_path, &args );
		gahp->setNotificationTimerId( scheddPollTid );
		gahp->setMode( GahpClient::normal );
		gahp->setTimeout( CondorJob::gahpCallTimeout );

		ping_gahp = new GahpClient( buff.c_str(), gahp_path, &args );
		ping_gahp->setNotificationTimerId( pingTimerId );
		ping_gahp->setMode( GahpClient::normal );
		ping_gahp->setTimeout( CondorJob::gahpCallTimeout );

		lease_gahp = new GahpClient( buff.c_str(), gahp_path, &args );
		lease_gahp->setNotificationTimerId( updateLeasesTimerId );
		lease_gahp->setMode( GahpClient::normal );
		lease_gahp->setTimeout( CondorJob::gahpCallTimeout );

		free( gahp_path );
	}
}

CondorResource::~CondorResource()
{
	ResourcesByName.erase( HashName( resourceName, poolName, proxyFQAN, m_scitokensFile ) );

		// Make sure we don't leak a ScheddPollInfo. If there are other
		// CondorResources that still want to use it, they'll recreate it.
		// Don't delete it if we know another CondorResource is doing a
		// poll of the remote schedd right now.
		// TODO Track how many CondorResources are still using this
		//   ScheddPollInfo and delete it only if we're the last one.
	ScheddPollInfo *poll_info = NULL;
	PollInfoByName.lookup( HashName( scheddName, poolName, NULL, "" ), poll_info );
	if ( poll_info && ( poll_info->m_pollActive == false ||
		 scheddStatusActive == true ) ) {
		PollInfoByName.remove( HashName( scheddName, poolName, NULL, "" ) );
		delete poll_info;
	}
	if ( proxySubject != NULL ) {
		free( proxySubject );
	}
	free( proxyFQAN );
	if ( scheddPollTid != TIMER_UNSET ) {
		daemonCore->Cancel_Timer( scheddPollTid );
	}
	if ( gahp != NULL ) {
		delete gahp;
	}
	if ( ping_gahp != NULL ) {
		delete ping_gahp;
	}
	if ( lease_gahp != NULL ) {
		delete lease_gahp;
	}
	if ( scheddName != NULL ) {
		free( scheddName );
	}
	if ( poolName != NULL ) {
		free( poolName );
	}
}

void CondorResource::Reconfig()
{
	BaseResource::Reconfig();
}

const char *CondorResource::ResourceType()
{
	return "condor";
}

const char *CondorResource::GetHashName()
{
	return HashName( resourceName, poolName, proxyFQAN, m_scitokensFile ).c_str();
}

void CondorResource::PublishResourceAd( ClassAd *resource_ad )
{
	BaseResource::PublishResourceAd( resource_ad );

	std::string buff;

	formatstr( buff, "condor %s %s", resourceName, poolName );
	resource_ad->Assign( ATTR_NAME, buff );
	if ( proxySubject ) {
		resource_ad->Assign( ATTR_X509_USER_PROXY_SUBJECT, proxySubject );
	}
	if ( proxyFQAN ) {
		resource_ad->Assign( ATTR_X509_USER_PROXY_FQAN, proxyFQAN );
	}
	if ( !m_scitokensFile.empty() ) {
		resource_ad->Assign( ATTR_SCITOKENS_FILE, m_scitokensFile );
	}

	gahp->PublishStats( resource_ad );
}

void CondorResource::CondorRegisterJob( CondorJob *job, const char *submitter_id )
{
	BaseResource::RegisterJob( job );

	if ( submitter_ids.contains( submitter_id ) == false ) {
		submitter_ids.append( submitter_id );
		if ( submitter_constraint.empty() ) {
			formatstr( submitter_constraint, "(%s=?=\"%s\")",
										  ATTR_SUBMITTER_ID,
										  submitter_id );
		} else {
			formatstr_cat( submitter_constraint, "||(%s=?=\"%s\")",
											  ATTR_SUBMITTER_ID,
											  submitter_id );
		}
	}
}

void CondorResource::UnregisterJob( BaseJob *base_job )
{
	CondorJob *job = dynamic_cast<CondorJob*>( base_job );

	ScheddPollInfo *poll_info = NULL;
	PollInfoByName.lookup( HashName( scheddName, poolName, NULL, "" ), poll_info );
	if ( poll_info ) {
		poll_info->m_submittedJobs.Delete( job );
	}

		// This may call delete, so don't put anything after it!
	BaseResource::UnregisterJob( job );
}

// Return true if the given error message from the gahp indicates that
// the remote schedd isn't working. Authentication or authorization
// failures don't count.
bool CondorResource::GahpErrorResourceDown( const char *errmsg )
{
	if ( errmsg == NULL ) {
		return false;
	}
	if ( strstr( errmsg, "Failed to connect to" ) ||
		 strstr( errmsg, "Error locating schedd" ) ) {
		return true;
	} else {
		return false;
	}
}

void CondorResource::DoScheddPoll()
{
	int rc;
	ScheddPollInfo *poll_info = NULL;

	if ( ( registeredJobs.IsEmpty() || resourceDown ) &&
		 scheddStatusActive == false ) {
			// No jobs or we can't talk to the schedd, so no point
			// in polling
		daemonCore->Reset_Timer( scheddPollTid, BatchStatusInterval() );
		return;
	}

	if ( gahp->isStarted() == false ) {
		// The gahp isn't started yet. Wait a few seconds for a CondorJob
		// object to start it (and possibly initialize x509 credentials).
		daemonCore->Reset_Timer( scheddPollTid, 5 );
		return;
	}

	PollInfoByName.lookup( HashName( scheddName, poolName, NULL, "" ), poll_info );

	daemonCore->Reset_Timer( scheddPollTid, TIMER_NEVER );

	if ( scheddStatusActive == false ) {

			// We share polls across all CondorResource objects going to
			// the same schedd. If another object has done a poll
			// recently, then don't bother doing one ourselves.
		if ( poll_info  == NULL ) {
			poll_info = new ScheddPollInfo;
			poll_info->m_lastPoll = 0;
			poll_info->m_pollActive = false;
			PollInfoByName.insert( HashName( scheddName, poolName, NULL, "" ),
								   poll_info );
		}

		if ( poll_info->m_pollActive == true ||
			 poll_info->m_lastPoll + BatchStatusInterval() > time(NULL) ) {
			daemonCore->Reset_Timer( scheddPollTid, BatchStatusInterval() );
			return;
		}

			// start schedd status command
		dprintf( D_FULLDEBUG, "Starting collective poll: %s\n",
				 scheddName );
		std::string constraint;

			// create a list of jobs we expect to hear about in our
			// status command
			// Since we're sharing the results of this status command with
			// all CondorResource objects going to the same schedd, look
			// for their jobs as well.
		poll_info->m_submittedJobs.Rewind();
		while ( poll_info->m_submittedJobs.Next() ) {
			poll_info->m_submittedJobs.DeleteCurrent();
		}
		BaseJob *job;
		std::string job_id;
		for (auto &elem : ResourcesByName) {
			CondorResource *next_resource = elem.second;
			if ( strcmp( scheddName, next_resource->scheddName ) ||
				 strcmp( poolName ? poolName : "",
						 next_resource->poolName ? next_resource->poolName : "" ) ) {
				continue;
			}

			next_resource->registeredJobs.Rewind();
			while ( ( job = next_resource->registeredJobs.Next() ) ) {
				if ( job->jobAd->LookupString( ATTR_GRID_JOB_ID, job_id ) ) {
					poll_info->m_submittedJobs.Append( (CondorJob *)job );
				}
			}
		}

		formatstr( constraint, "(%s)", submitter_constraint.c_str() );

		rc = gahp->condor_job_status_constrained( scheddName,
												  constraint.c_str(),
												  NULL, NULL );

		if ( rc != GAHPCLIENT_COMMAND_PENDING ) {
			dprintf( D_ALWAYS,
					 "gahp->condor_job_status_constrained returned %d for remote schedd: %s\n",
					 rc, scheddName );
			EXCEPT( "condor_job_status_constrained failed!" );
		}
		scheddStatusActive = true;
		poll_info->m_pollActive = true;

	} else {

			// finish schedd status command
		int num_status_ads;
		ClassAd **status_ads = NULL;

		ASSERT( poll_info );

		rc = gahp->condor_job_status_constrained( NULL, NULL,
												  &num_status_ads,
												  &status_ads );

		if ( rc == GAHPCLIENT_COMMAND_PENDING ) {
			return;
		} else if ( rc != 0 ) {
			dprintf( D_ALWAYS,
					 "gahp->condor_job_status_constrained returned %d for remote schedd %s\n",
					 rc, scheddName );
			dprintf( D_ALWAYS, "Requesting ping of resource\n" );
			RequestPing( NULL );
		}

		if ( rc == 0 ) {
			for ( int i = 0; i < num_status_ads; i++ ) {
				int cluster, proc;
				std::string job_id_string;
				CondorJob *job;

				if( status_ads[i] == NULL ) {
					dprintf(D_ALWAYS, "DoScheddPoll was given null pointer for classad #%d\n", i);
					continue;
				}

				status_ads[i]->LookupInteger( ATTR_CLUSTER_ID, cluster );
				status_ads[i]->LookupInteger( ATTR_PROC_ID, proc );

				formatstr( job_id_string, "condor %s %s %d.%d", scheddName,
									   poolName, cluster, proc );

				auto itr = BaseJob::JobsByRemoteId.find(job_id_string);
				if ( itr != BaseJob::JobsByRemoteId.end() ) {
					job = dynamic_cast<CondorJob*>(itr->second);
					job->NotifyNewRemoteStatus( status_ads[i] );
					poll_info->m_submittedJobs.Delete( job );
				} else {
					delete status_ads[i];
				}
			}

			poll_info->m_lastPoll = time(NULL);
		}
		poll_info->m_pollActive = false;

		if ( status_ads != NULL ) {
			free( status_ads );
		}

			// Check if any jobs were missing from the status result
		if ( rc == 0 ) {
			CondorJob *job;
			std::string job_id;
			poll_info->m_submittedJobs.Rewind();
			while ( ( job = poll_info->m_submittedJobs.Next() ) ) {
				if ( job->jobAd->LookupString( ATTR_GRID_JOB_ID, job_id ) ) {
						// We should have gotten a status ad for this job,
						// but didn't. Tell the job that there may be
						// something wrong by giving it a NULL status ad.
					job->NotifyNewRemoteStatus( NULL );
				}
				poll_info->m_submittedJobs.DeleteCurrent();
			}
		}

		scheddStatusActive = false;

		dprintf( D_FULLDEBUG, "Collective poll complete: %s\n", scheddName );

		daemonCore->Reset_Timer( scheddPollTid, BatchStatusInterval() );
	}
}

void CondorResource::DoPing( unsigned& ping_delay, bool& ping_complete,
							 bool& ping_succeeded )
{
	int rc;
	int num_status_ads = 0;
	ClassAd **status_ads = NULL;

dprintf(D_FULLDEBUG,"*** DoPing called\n");
	if ( ping_gahp->isStarted() == false ) {
		dprintf( D_ALWAYS,"gahp server not up yet, delaying ping\n" );
		ping_delay = 5;
		return;
	}

	ping_delay = 0;

	rc = ping_gahp->condor_job_status_constrained( scheddName, "False",
												   &num_status_ads,
												   &status_ads );
	ASSERT( num_status_ads == 0 );
	ASSERT( status_ads == NULL );

	if ( rc == GAHPCLIENT_COMMAND_PENDING ) {
		ping_complete = false;
	} else if ( rc != 0 ) {
		ping_complete = true;
		if ( GahpErrorResourceDown( ping_gahp->getErrorString() ) ) {
			ping_succeeded = false;
		} else {
			ping_succeeded = true;
		}
	} else {
		ping_complete = true;
		ping_succeeded = true;
	}
}

void CondorResource::DoUpdateLeases( unsigned& update_delay,
									 bool& update_complete,
									 SimpleList<PROC_ID>& update_succeeded )
{
	int rc;
	BaseJob *curr_job;
	SimpleList<PROC_ID> jobs;
	SimpleList<int> expirations;
	SimpleList<PROC_ID> updated;

dprintf(D_FULLDEBUG,"*** DoUpdateLeases called\n");
	if ( lease_gahp->isStarted() == false ) {
		dprintf( D_ALWAYS,"gahp server not up yet, delaying lease update\n" );
		update_delay = 5;
		return;
	}

	update_delay = 0;

	if ( leaseUpdates.IsEmpty() ) {
		dprintf( D_FULLDEBUG, "*** Job lease list empty, returning success immediately\n" );
		update_complete = true;
		return;
	}

	if ( updateLeasesCmdActive == false ) {
		leaseUpdates.Rewind();
		while ( leaseUpdates.Next( curr_job ) ) {
				// TODO When remote-job-id is homogenized and stored in
				//   BaseJob, BaseResource can skip jobs that don't have a
				//   a remote-job-id yet
			if ( ((CondorJob*)curr_job)->remoteJobId.cluster != 0 ) {
				jobs.Append( ((CondorJob*)curr_job)->remoteJobId );
				expirations.Append( m_sharedLeaseExpiration );
			}
		}
	}

	rc = lease_gahp->condor_job_update_lease( scheddName, jobs, expirations,
											  updated );

	if ( rc == GAHPCLIENT_COMMAND_PENDING ) {
		update_complete = false;
	} else if ( rc != 0 ) {
dprintf( D_FULLDEBUG, "*** Lease update failed!\n" );
		update_complete = true;
	} else {
dprintf( D_FULLDEBUG, "*** Lease udpate succeeded!\n" );
		update_complete = true;

		PROC_ID curr_id;
		std::string id_str;
		updated.Rewind();
		while ( updated.Next( curr_id ) ) {
			formatstr( id_str, "condor %s %s %d.%d", scheddName, poolName,
							curr_id.cluster, curr_id.proc );
			auto itr = BaseJob::JobsByRemoteId.find(id_str);
			if ( itr != BaseJob::JobsByRemoteId.end() ) {
				update_succeeded.Append( itr->second->procID );
			}
		}
	}
}


text:
layout: post
title:  "[Pluralsight] Github Guide for Beginners."
date:   2016-1-12 19:30:00
---

This is a post I did over at Pluralsight about Github and how to navigate and use it. It is aimed at the very new beginners, and may be a little too bland for seasoned veterns.

[View the Full Github Article Here...](http://blog.pluralsight.com/github-tutorial)


text:
require 'rubygems'
require 'ernie'

module RubyExample
  def add(a, b)
    a + b
  end
end

Ernie.expose(:ruby_example, RubyExample)


text:
export * from './app.component';
export * from './app.module';
//# sourceMappingURL=G:/wwwRoot/AngularJS/Material-Design-AngularJS2-App/MDA2A/src/app/index.js.map


text:
package fi.kela.kanta.to;

import fi.kela.kanta.interfaces.Osoite;

public class OsoiteTO implements Osoite {

    private static final long serialVersionUID = -4222164103902178L;
    // Katuosoite:String
    private String katuosoite;
    // Maa:String
    private String maa;
    // Postinumero:String
    private String postinumero;
    // Postitoimipaikka:String
    private String postitoimipaikka;

    @Override
    public String getKatuosoite() {
        return katuosoite;
    }

    @Override
    public void setKatuosoite(String katuosoite) {
        this.katuosoite = katuosoite;
    }

    @Override
    public String getMaa() {
        return maa;
    }

    @Override
    public void setMaa(String maa) {
        this.maa = maa;
    }

    @Override
    public String getPostinumero() {
        return postinumero;
    }

    @Override
    public void setPostinumero(String postinumero) {
        this.postinumero = postinumero;
    }

    @Override
    public String getPostitoimipaikka() {
        return postitoimipaikka;
    }

    @Override
    public void setPostitoimipaikka(String postitoimipaikka) {
        this.postitoimipaikka = postitoimipaikka;
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();
        sb.append("Osoite [katuosoite: ").append(getKatuosoite());
        sb.append(", postinumero: ").append(getPostinumero());
        sb.append(", postitoimipaikka: ").append(getPostitoimipaikka());
        sb.append(", maa: ").append(getMaa());
        sb.append("]");
        return sb.toString();
    }
}


text:
layout: post
title: Github Analytics
---
The arrow marks the time when I started to work for IBM.
![Here it is](http://i.imgur.com/ZO9QQeV.png)

I like all those pretty github graphs :)


text:
ASN_MODULE_SOURCES=	\
	LDAPMessage.c	\
	MessageID.c	\
	LDAPString.c	\
	LDAPOID.c	\
	LDAPDN.c	\
	RelativeLDAPDN.c	\
	AttributeDescription.c	\
	AttributeValue.c	\
	AttributeValueAssertion.c	\
	AssertionValue.c	\
	PartialAttribute.c	\
	Attribute.c	\
	MatchingRuleId.c	\
	LDAPResult.c	\
	Referral.c	\
	URI.c	\
	Controls.c	\
	Control.c	\
	BindRequest.c	\
	AuthenticationChoice.c	\
	SaslCredentials.c	\
	BindResponse.c	\
	UnbindRequest.c	\
	SearchRequest.c	\
	AttributeSelection.c	\
	Filter.c	\
	SubstringFilter.c	\
	MatchingRuleAssertion.c	\
	SearchResultEntry.c	\
	PartialAttributeList.c	\
	SearchResultReference.c	\
	SearchResultDone.c	\
	ModifyRequest.c	\
	ModifyResponse.c	\
	AddRequest.c	\
	AttributeList.c	\
	AddResponse.c	\
	DelRequest.c	\
	DelResponse.c	\
	ModifyDNRequest.c	\
	ModifyDNResponse.c	\
	CompareRequest.c	\
	CompareResponse.c	\
	AbandonRequest.c	\
	ExtendedRequest.c	\
	ExtendedResponse.c	\
	IntermediateResponse.c

ASN_MODULE_HEADERS=	\
	LDAPMessage.h	\
	MessageID.h	\
	LDAPString.h	\
	LDAPOID.h	\
	LDAPDN.h	\
	RelativeLDAPDN.h	\
	AttributeDescription.h	\
	AttributeValue.h	\
	AttributeValueAssertion.h	\
	AssertionValue.h	\
	PartialAttribute.h	\
	Attribute.h	\
	MatchingRuleId.h	\
	LDAPResult.h	\
	Referral.h	\
	URI.h	\
	Controls.h	\
	Control.h	\
	BindRequest.h	\
	AuthenticationChoice.h	\
	SaslCredentials.h	\
	BindResponse.h	\
	UnbindRequest.h	\
	SearchRequest.h	\
	AttributeSelection.h	\
	Filter.h	\
	SubstringFilter.h	\
	MatchingRuleAssertion.h	\
	SearchResultEntry.h	\
	PartialAttributeList.h	\
	SearchResultReference.h	\
	SearchResultDone.h	\
	ModifyRequest.h	\
	ModifyResponse.h	\
	AddRequest.h	\
	AttributeList.h	\
	AddResponse.h	\
	DelRequest.h	\
	DelResponse.h	\
	ModifyDNRequest.h	\
	ModifyDNResponse.h	\
	CompareRequest.h	\
	CompareResponse.h	\
	AbandonRequest.h	\
	ExtendedRequest.h	\
	ExtendedResponse.h	\
	IntermediateResponse.h

ASN_MODULE_HEADERS+=UTF8String.h
ASN_MODULE_HEADERS+=BOOLEAN.h
ASN_MODULE_SOURCES+=BOOLEAN.c
ASN_MODULE_HEADERS+=ENUMERATED.h
ASN_MODULE_SOURCES+=ENUMERATED.c
ASN_MODULE_HEADERS+=INTEGER.h
ASN_MODULE_HEADERS+=NativeEnumerated.h
ASN_MODULE_SOURCES+=INTEGER.c
ASN_MODULE_HEADERS+=NULL.h
ASN_MODULE_SOURCES+=NULL.c
ASN_MODULE_SOURCES+=NativeEnumerated.c
ASN_MODULE_HEADERS+=NativeInteger.h
ASN_MODULE_SOURCES+=NativeInteger.c
ASN_MODULE_SOURCES+=UTF8String.c
ASN_MODULE_HEADERS+=asn_SEQUENCE_OF.h
ASN_MODULE_SOURCES+=asn_SEQUENCE_OF.c
ASN_MODULE_HEADERS+=asn_SET_OF.h
ASN_MODULE_SOURCES+=asn_SET_OF.c
ASN_MODULE_HEADERS+=constr_CHOICE.h
ASN_MODULE_SOURCES+=constr_CHOICE.c
ASN_MODULE_HEADERS+=constr_SEQUENCE.h
ASN_MODULE_SOURCES+=constr_SEQUENCE.c
ASN_MODULE_HEADERS+=constr_SEQUENCE_OF.h
ASN_MODULE_SOURCES+=constr_SEQUENCE_OF.c
ASN_MODULE_HEADERS+=constr_SET_OF.h
ASN_MODULE_SOURCES+=constr_SET_OF.c
ASN_MODULE_HEADERS+=asn_application.h
ASN_MODULE_HEADERS+=asn_system.h
ASN_MODULE_HEADERS+=asn_codecs.h
ASN_MODULE_HEADERS+=asn_internal.h
ASN_MODULE_HEADERS+=OCTET_STRING.h
ASN_MODULE_SOURCES+=OCTET_STRING.c
ASN_MODULE_HEADERS+=BIT_STRING.h
ASN_MODULE_SOURCES+=BIT_STRING.c
ASN_MODULE_SOURCES+=asn_codecs_prim.c
ASN_MODULE_HEADERS+=asn_codecs_prim.h
ASN_MODULE_HEADERS+=ber_tlv_length.h
ASN_MODULE_SOURCES+=ber_tlv_length.c
ASN_MODULE_HEADERS+=ber_tlv_tag.h
ASN_MODULE_SOURCES+=ber_tlv_tag.c
ASN_MODULE_HEADERS+=ber_decoder.h
ASN_MODULE_SOURCES+=ber_decoder.c
ASN_MODULE_HEADERS+=der_encoder.h
ASN_MODULE_SOURCES+=der_encoder.c
ASN_MODULE_HEADERS+=constr_TYPE.h
ASN_MODULE_SOURCES+=constr_TYPE.c
ASN_MODULE_HEADERS+=constraints.h
ASN_MODULE_SOURCES+=constraints.c
ASN_MODULE_HEADERS+=xer_support.h
ASN_MODULE_SOURCES+=xer_support.c
ASN_MODULE_HEADERS+=xer_decoder.h
ASN_MODULE_SOURCES+=xer_decoder.c
ASN_MODULE_HEADERS+=xer_encoder.h
ASN_MODULE_SOURCES+=xer_encoder.c
ASN_MODULE_HEADERS+=per_support.h
ASN_MODULE_SOURCES+=per_support.c
ASN_MODULE_HEADERS+=per_decoder.h
ASN_MODULE_SOURCES+=per_decoder.c
ASN_MODULE_HEADERS+=per_encoder.h
ASN_MODULE_SOURCES+=per_encoder.c
ASN_MODULE_HEADERS+=per_opentype.h
ASN_MODULE_SOURCES+=per_opentype.c
ASN_CONVERTER_SOURCES+=ldap-server.c

lib_LTLIBRARIES=libsomething.la
libsomething_la_SOURCES=$(ASN_MODULE_SOURCES) $(ASN_MODULE_HEADERS)

# This file may be used as an input for make(3)
# Remove the lines below to convert it into a pure .am file
TARGET = ldap-server
CFLAGS += -I. -g
OBJS=${ASN_MODULE_SOURCES:.c=.o} ${ASN_CONVERTER_SOURCES:.c=.o}

all: $(TARGET)

$(TARGET): ${OBJS}
	$(CC) $(CFLAGS) -o $(TARGET) ${OBJS} $(LDFLAGS) $(LIBS)

.SUFFIXES:
.SUFFIXES: .c .o

.c.o:
	$(CC) $(CFLAGS) -o $@ -c $<

clean:
	rm -f $(TARGET)
	rm -f $(OBJS)

regen: regenerate-from-asn1-source

regenerate-from-asn1-source:
	asn1c -fcompound-names -fskeletons-copy Lightweight-Directory-Access-Protocol-V3.asn1


text:
using System;
using Server;
using Server.Mobiles;
using Server.Gumps;
using Server.Network;

namespace Server.Items
{
	public class StatCapScroll : SpecialScroll
	{
		public override int Message { get { return 1049469; } } /* Using a scroll increases the maximum amount of a specific skill or your maximum statistics.
																* When used, the effect is not immediately seen without a gain of points with that skill or statistics.
																* You can view your maximum skill values in your skills window.
																* You can view your maximum statistic value in your statistics window. */
		public override int Title
		{
			get
			{
				int level = ( (int)Value - 230 ) / 5;

				if ( level >= 0 && level <= 4 && Value % 5 == 0 )
					return 1049458 + level;	/* Wonderous Scroll (+5 Maximum Stats): OR
											* Exalted Scroll (+10 Maximum Stats): OR
											* Mythical Scroll (+15 Maximum Stats): OR
											* Legendary Scroll (+20 Maximum Stats): OR
											* Ultimate Scroll (+25 Maximum Stats): */

				return 0;
			}
		}

		public override string DefaultTitle { get { return String.Format( "<basefont color=#FFFFFF>Power Scroll ({0}{1} Maximum Stats):</basefont>", ( (int)Value - 225 ) >= 0 ? "+" : "", (int)Value - 225 ); } }

		public StatCapScroll() : this( 105 )
		{
		}

		[Constructable]
		public StatCapScroll( int value ) : base( SkillName.Alchemy, value )
		{
			Hue = 0x481;
		}

		public StatCapScroll( Serial serial ) : base( serial )
		{
		}

		public override void AddNameProperty(ObjectPropertyList list)
		{
			int level = ( (int)Value - 230 ) / 5;

			if ( level >= 0 && level <= 4 && (int)Value % 5 == 0 )
				list.Add( 1049463 + level, "#1049476" );	/* a wonderous scroll of ~1_type~ (+5 Maximum Stats) OR
															* an exalted scroll of ~1_type~ (+10 Maximum Stats) OR
															* a mythical scroll of ~1_type~ (+15 Maximum Stats) OR
															* a legendary scroll of ~1_type~ (+20 Maximum Stats) OR
															* an ultimate scroll of ~1_type~ (+25 Maximum Stats) */
			else
				list.Add( "a scroll of power ({0}{1} Maximum Stats)", (Value - 225) >= 0 ? "+" : "", Value - 225 );
		}

		public override void OnSingleClick( Mobile from )
		{
			int level = ( (int)Value - 230 ) / 5;

			if ( level >= 0 && level <= 4 && (int)Value % 5 == 0 )
				base.LabelTo( from, 1049463 + level, "#1049476" );
			else
				base.LabelTo( from, "a scroll of power ({0}{1} Maximum Stats)", (Value - 225) >= 0 ? "+" : "", Value - 225 );
		}

		public override bool CanUse( Mobile from )
		{
			if ( !base.CanUse( from ) )
				return false;

			int newValue = (int)Value;

			if ( from is PlayerMobile && ((PlayerMobile)from).HasStatReward )
				newValue += 5;

			if ( from.StatCap >= newValue )
			{
				from.SendLocalizedMessage( 1049510 ); // Your stats are too high for this power scroll.
				return false;
			}

			return true;
		}

		public override void Use( Mobile from )
		{
			if ( !CanUse( from ) )
				return;

			from.SendLocalizedMessage( 1049512 ); // You feel a surge of magic as the scroll enhances your powers!

			if ( from is PlayerMobile && ((PlayerMobile)from).HasStatReward )
				from.StatCap = (int)Value + 5;
			else
				from.StatCap = (int)Value;

			Effects.SendLocationParticles( EffectItem.Create( from.Location, from.Map, EffectItem.DefaultDuration ), 0, 0, 0, 0, 0, 5060, 0 );
			Effects.PlaySound( from.Location, from.Map, 0x243 );

			Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 6, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
			Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 4, from.Y - 6, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );
			Effects.SendMovingParticles( new Entity( Serial.Zero, new Point3D( from.X - 6, from.Y - 4, from.Z + 15 ), from.Map ), from, 0x36D4, 7, 0, false, true, 0x497, 0, 9502, 1, 0, (EffectLayer)255, 0x100 );

			Effects.SendTargetParticles( from, 0x375A, 35, 90, 0x00, 0x00, 9502, (EffectLayer)255, 0x100 );

			Delete();
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = ( InheritsItem ? 0 : reader.ReadInt() ); //Required for SpecialScroll insertion

			LootType = LootType.Cursed;
			Insured = false;
		}
	}
}


text:
<?php

namespace Umulmrum\Holiday;

use Umulmrum\Holiday\Assert\Assert;
use Umulmrum\Holiday\Model\HolidayList;
use Umulmrum\Holiday\Resolver\ClassNameResolver;
use Umulmrum\Holiday\Resolver\IsoResolver;
use Umulmrum\Holiday\Resolver\ProviderResolverInterface;
use Umulmrum\Holiday\Resolver\ResolverHandler;
use Umulmrum\Holiday\Resolver\ResolverHandlerInterface;

final class HolidayCalculator implements HolidayCalculatorInterface
{
    use Assert;

    /**
     * @var ProviderResolverInterface[]
     */
    private $providerResolvers = [];
    /**
     * @var ResolverHandlerInterface
     */
    private $resolverHandler;

    public function __construct(ResolverHandlerInterface $resolverHandler = null)
    {
        $this->resolverHandler = $resolverHandler ?? new ResolverHandler([new ClassNameResolver(), new IsoResolver()]);
    }

    /**
     * {@inheritdoc}
     */
    public function calculate($holidayProviders, $years): HolidayList
    {
        $finalYears = $this->interpretYears($years);

        $holidays = new HolidayList();
        foreach ($this->resolverHandler->resolve($holidayProviders) as $holidayProvider) {
            foreach ($finalYears as $year) {
                $holidays->addAll($holidayProvider->calculateHolidaysForYear($year));
            }
        }

        return $holidays;
    }

    /**
     * @param int|int[] $years
     *
     * @return int[]
     *
     * * @throws \InvalidArgumentException
     */
    private function interpretYears($years): array
    {
        if (\is_int($years)) {
            return [$years];
        }

        /** @psalm-suppress RedundantConditionGivenDocblockType */
        if (\is_array($years)) {
            $this->assertIntArray($years);

            return $years;
        }

        throw new \InvalidArgumentException('Year needs to be either int or an array of int');
    }
}


text:
CREATE TABLE {{{tablePrefix}}}{{tableName}}{{{tableSuffix}}}
    ({{#each_with_index columns}}{{#if index}}, {{/if}}{{{../fieldPrefix}}}{{name}}{{{../fieldSuffix}}} {{db_type}}{{/each_with_index}})
{{separator}}

INSERT INTO {{{tablePrefix}}}{{tableName}}{{{tableSuffix}}}
    ({{#each_with_index columns}}{{#if index}}, {{/if}}{{{../fieldPrefix}}}{{name}}{{{../fieldSuffix}}}{{/each_with_index}})
VALUES
    {{#each_with_index data}}{{#if index}},
    {{/if}}({{#each_with_index r}}{{#if index}}, {{/if}}{{formatted_field ../..}}{{/each_with_index}}){{/each_with_index}}
{{separator}}


text:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class AnagramMain {

	// To be able to test with a Junit file
	public static Scanner console = new Scanner(System.in);

	public static PrintStream out = System.out;

	public static void main(String[] args) throws FileNotFoundException {
		out.println("Welcome to the csc143 anagram solver.");
		out.println();

		// open the dictionary file
		out.print("What is the name of the dictionary file? ");
		Scanner input = new Scanner(new File(console.nextLine()));

		// read dictionary into an ArrayList
		List<String> dictionary = new ArrayList<String>();
		while (input.hasNextLine()) {
			dictionary.add(input.nextLine());
		}

		// solve anagrams
		List<String> dictionary2 = Collections.unmodifiableList(dictionary);
		AnagramSolver solver = new AnagramSolver(dictionary2);
		String phrase;
		do {
			out.println();
			out.print("phrase to scramble (return to quit)? ");
			phrase = console.nextLine();
			if (phrase.length() != 0) {
				out.print("Max words to include (0 for no max)? ");
				int max = console.nextInt();
				console.nextLine(); // to skip newline after int
				solver.print(phrase, max);
			}
		} while (phrase.length() > 0);

		input.close();
	}
}