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

using UnityEngine;
using com.adjust.sdk.test;

namespace com.adjust.sdk
{
#if UNITY_ANDROID
    public class AdjustAndroid
    {
        private const string sdkPrefix = "unity4.14.1";
        private static bool launchDeferredDeeplink = true;

        private static AndroidJavaClass ajcAdjust = new AndroidJavaClass("com.adjust.sdk.Adjust");
        // TODO: Check whether currentActivity should be disposed after usage.
        private static AndroidJavaObject ajoCurrentActivity = new AndroidJavaClass
            ("com.unity3d.player.UnityPlayer").GetStatic<AndroidJavaObject>("currentActivity");

        private static DeferredDeeplinkListener onDeferredDeeplinkListener;
        private static AttributionChangeListener onAttributionChangedListener;
        private static EventTrackingFailedListener onEventTrackingFailedListener;
        private static EventTrackingSucceededListener onEventTrackingSucceededListener;
        private static SessionTrackingFailedListener onSessionTrackingFailedListener;
        private static SessionTrackingSucceededListener onSessionTrackingSucceededListener;

        public static void Start(AdjustConfig adjustConfig)
        {
            // Get environment variable.
            AndroidJavaObject ajoEnvironment = adjustConfig.environment == AdjustEnvironment.Sandbox ?
                new AndroidJavaClass("com.adjust.sdk.AdjustConfig").GetStatic<AndroidJavaObject>("ENVIRONMENT_SANDBOX") :
                    new AndroidJavaClass("com.adjust.sdk.AdjustConfig").GetStatic<AndroidJavaObject>("ENVIRONMENT_PRODUCTION");

            // Create adjust config object.
            AndroidJavaObject ajoAdjustConfig;

            // Check if suppress log leve is supported.
            if (adjustConfig.allowSuppressLogLevel != null)
            {
                ajoAdjustConfig = new AndroidJavaObject("com.adjust.sdk.AdjustConfig", ajoCurrentActivity, adjustConfig.appToken, ajoEnvironment, adjustConfig.allowSuppressLogLevel);
            }
            else
            {
                ajoAdjustConfig = new AndroidJavaObject("com.adjust.sdk.AdjustConfig", ajoCurrentActivity, adjustConfig.appToken, ajoEnvironment);
            }

            // Check if deferred deeplink should be launched by SDK.
            launchDeferredDeeplink = adjustConfig.launchDeferredDeeplink;

            // Check log level.
            if (adjustConfig.logLevel != null)
            {
                AndroidJavaObject ajoLogLevel;

                if (adjustConfig.logLevel.Value.ToUppercaseString().Equals("SUPPRESS"))
                {
                    ajoLogLevel = new AndroidJavaClass("com.adjust.sdk.LogLevel").GetStatic<AndroidJavaObject>("SUPRESS");
                }
                else
                {
                    ajoLogLevel = new AndroidJavaClass("com.adjust.sdk.LogLevel").GetStatic<AndroidJavaObject>(adjustConfig.logLevel.Value.ToUppercaseString());
                }

                if (ajoLogLevel != null)
                {
                    ajoAdjustConfig.Call("setLogLevel", ajoLogLevel);
                }
            }

            // Set unity SDK prefix.
            ajoAdjustConfig.Call("setSdkPrefix", sdkPrefix);

            // Check if user has configured the delayed start option.
            if (adjustConfig.delayStart != null)
            {
                ajoAdjustConfig.Call("setDelayStart", adjustConfig.delayStart);
            }

            // Check event buffering setting.
            if (adjustConfig.eventBufferingEnabled != null)
            {
                AndroidJavaObject ajoIsEnabled = new AndroidJavaObject("java.lang.Boolean", adjustConfig.eventBufferingEnabled.Value);
                ajoAdjustConfig.Call("setEventBufferingEnabled", ajoIsEnabled);
            }

            // Check if user enabled tracking in the background.
            if (adjustConfig.sendInBackground != null)
            {
                ajoAdjustConfig.Call("setSendInBackground", adjustConfig.sendInBackground.Value);
            }

            // Check if user has set user agent value.
            if (adjustConfig.userAgent != null)
            {
                ajoAdjustConfig.Call("setUserAgent", adjustConfig.userAgent);
            }

            // Check if user has set default process name.
            if (!String.IsNullOrEmpty(adjustConfig.processName))
            {
                ajoAdjustConfig.Call("setProcessName", adjustConfig.processName);
            }

            // Check if user has set default tracker token.
            if (adjustConfig.defaultTracker != null)
            {
                ajoAdjustConfig.Call("setDefaultTracker", adjustConfig.defaultTracker);
            }

            // Check if user has set app secret.
            if (IsAppSecretSet(adjustConfig))
            {
                ajoAdjustConfig.Call("setAppSecret",
                    adjustConfig.secretId.Value,
                    adjustConfig.info1.Value,
                    adjustConfig.info2.Value,
                    adjustConfig.info3.Value,
                    adjustConfig.info4.Value);
            }

            // Check if user has set device as known.
            if (adjustConfig.isDeviceKnown.HasValue)
            {
                ajoAdjustConfig.Call("setDeviceKnown", adjustConfig.isDeviceKnown.Value);
            }

            // Check if user has enabled reading of IMEI and MEID.
            if (adjustConfig.readImei.HasValue)
            {
                ajoAdjustConfig.Call("setReadMobileEquipmentIdentity", adjustConfig.readImei.Value);
            }

            // Check attribution changed delagate setting.
            if (adjustConfig.attributionChangedDelegate != null)
            {
                onAttributionChangedListener = new AttributionChangeListener(adjustConfig.attributionChangedDelegate);
                ajoAdjustConfig.Call("setOnAttributionChangedListener", onAttributionChangedListener);
            }

            // Check event success delegate setting.
            if (adjustConfig.eventSuccessDelegate != null)
            {
                onEventTrackingSucceededListener = new EventTrackingSucceededListener(adjustConfig.eventSuccessDelegate);
                ajoAdjustConfig.Call("setOnEventTrackingSucceededListener", onEventTrackingSucceededListener);
            }

            // Check event failure delagate setting.
            if (adjustConfig.eventFailureDelegate != null)
            {
                onEventTrackingFailedListener = new EventTrackingFailedListener(adjustConfig.eventFailureDelegate);
                ajoAdjustConfig.Call("setOnEventTrackingFailedListener", onEventTrackingFailedListener);
            }

            // Check session success delegate setting.
            if (adjustConfig.sessionSuccessDelegate != null)
            {
                onSessionTrackingSucceededListener = new SessionTrackingSucceededListener(adjustConfig.sessionSuccessDelegate);
                ajoAdjustConfig.Call("setOnSessionTrackingSucceededListener", onSessionTrackingSucceededListener);
            }

            // Check session failure delegate setting.
            if (adjustConfig.sessionFailureDelegate != null)
            {
                onSessionTrackingFailedListener = new SessionTrackingFailedListener(adjustConfig.sessionFailureDelegate);
                ajoAdjustConfig.Call("setOnSessionTrackingFailedListener", onSessionTrackingFailedListener);
            }

            // Check deferred deeplink delegate setting.
            if (adjustConfig.deferredDeeplinkDelegate != null)
            {
                onDeferredDeeplinkListener = new DeferredDeeplinkListener(adjustConfig.deferredDeeplinkDelegate);
                ajoAdjustConfig.Call("setOnDeeplinkResponseListener", onDeferredDeeplinkListener);
            }

            // Initialise and start the SDK.
            ajcAdjust.CallStatic("onCreate", ajoAdjustConfig);
            ajcAdjust.CallStatic("onResume");
        }

        public static void TrackEvent(AdjustEvent adjustEvent)
        {
            AndroidJavaObject ajoAdjustEvent = new AndroidJavaObject("com.adjust.sdk.AdjustEvent", adjustEvent.eventToken);

            // Check if user has set revenue for the event.
            if (adjustEvent.revenue != null)
            {
                ajoAdjustEvent.Call("setRevenue", (double)adjustEvent.revenue, adjustEvent.currency);
            }

            // Check if user has added any callback parameters to the event.
            if (adjustEvent.callbackList != null)
            {
                for (int i = 0; i < adjustEvent.callbackList.Count; i += 2)
                {
                    string key = adjustEvent.callbackList[i];
                    string value = adjustEvent.callbackList[i + 1];
                    ajoAdjustEvent.Call("addCallbackParameter", key, value);
                }
            }

            // Check if user has added any partner parameters to the event.
            if (adjustEvent.partnerList != null)
            {
                for (int i = 0; i < adjustEvent.partnerList.Count; i += 2)
                {
                    string key = adjustEvent.partnerList[i];
                    string value = adjustEvent.partnerList[i + 1];
                    ajoAdjustEvent.Call("addPartnerParameter", key, value);
                }
            }

            // Check if user has added transaction ID to the event.
            if (adjustEvent.transactionId != null)
            {
                ajoAdjustEvent.Call("setOrderId", adjustEvent.transactionId);
            }

            // Track the event.
            ajcAdjust.CallStatic("trackEvent", ajoAdjustEvent);
        }

        public static bool IsEnabled()
        {
            return ajcAdjust.CallStatic<bool>("isEnabled");
        }

        public static void SetEnabled(bool enabled)
        {
            ajcAdjust.CallStatic("setEnabled", enabled);
        }

        public static void SetOfflineMode(bool enabled)
        {
            ajcAdjust.CallStatic("setOfflineMode", enabled);
        }

        public static void SendFirstPackages()
        {
            ajcAdjust.CallStatic("sendFirstPackages");
        }

        public static void SetDeviceToken(string deviceToken)
        {
            ajcAdjust.CallStatic("setPushToken", deviceToken, ajoCurrentActivity);
        }

        public static string GetAdid()
        {
            return ajcAdjust.CallStatic<string>("getAdid");
        }

        public static void GdprForgetMe()
        {
            ajcAdjust.CallStatic("gdprForgetMe", ajoCurrentActivity);
        }

        public static AdjustAttribution GetAttribution()
        {
            try
            {
                AndroidJavaObject ajoAttribution = ajcAdjust.CallStatic<AndroidJavaObject>("getAttribution");
                if (null == ajoAttribution)
                {
                    return null;
                }

                AdjustAttribution adjustAttribution = new AdjustAttribution();
                adjustAttribution.trackerName = ajoAttribution.Get<string>(AdjustUtils.KeyTrackerName);
                adjustAttribution.trackerToken = ajoAttribution.Get<string>(AdjustUtils.KeyTrackerToken);
                adjustAttribution.network = ajoAttribution.Get<string>(AdjustUtils.KeyNetwork);
                adjustAttribution.campaign = ajoAttribution.Get<string>(AdjustUtils.KeyCampaign);
                adjustAttribution.adgroup = ajoAttribution.Get<string>(AdjustUtils.KeyAdgroup);
                adjustAttribution.creative = ajoAttribution.Get<string>(AdjustUtils.KeyCreative);
                adjustAttribution.clickLabel = ajoAttribution.Get<string>(AdjustUtils.KeyClickLabel);
                adjustAttribution.adid = ajoAttribution.Get<string>(AdjustUtils.KeyAdid);
                return adjustAttribution;
            }
            catch (Exception) {}

            return null;
        }

        public static void AddSessionPartnerParameter(string key, string value)
        {
            if (ajcAdjust == null)
            {
                ajcAdjust = new AndroidJavaClass("com.adjust.sdk.Adjust");
            }
            ajcAdjust.CallStatic("addSessionPartnerParameter", key, value);
        }

        public static void AddSessionCallbackParameter(string key, string value)
        {
            if (ajcAdjust == null)
            {
                ajcAdjust = new AndroidJavaClass("com.adjust.sdk.Adjust");
            }
            ajcAdjust.CallStatic("addSessionCallbackParameter", key, value);
        }

        public static void RemoveSessionPartnerParameter(string key)
        {
            if (ajcAdjust == null)
            {
                ajcAdjust = new AndroidJavaClass("com.adjust.sdk.Adjust");
            }
            ajcAdjust.CallStatic("removeSessionPartnerParameter", key);
        }

        public static void RemoveSessionCallbackParameter(string key)
        {
            if (ajcAdjust == null)
            {
                ajcAdjust = new AndroidJavaClass("com.adjust.sdk.Adjust");
            }
            ajcAdjust.CallStatic("removeSessionCallbackParameter", key);
        }

        public static void ResetSessionPartnerParameters()
        {
            if (ajcAdjust == null)
            {
                ajcAdjust = new AndroidJavaClass("com.adjust.sdk.Adjust");
            }
            ajcAdjust.CallStatic("resetSessionPartnerParameters");
        }

        public static void ResetSessionCallbackParameters()
        {
            if (ajcAdjust == null)
            {
                ajcAdjust = new AndroidJavaClass("com.adjust.sdk.Adjust");
            }
            ajcAdjust.CallStatic("resetSessionCallbackParameters");
        }

        public static void AppWillOpenUrl(string url)
        {
            AndroidJavaClass ajcUri = new AndroidJavaClass("android.net.Uri");
            AndroidJavaObject ajoUri = ajcUri.CallStatic<AndroidJavaObject>("parse", url);
            ajcAdjust.CallStatic("appWillOpenUrl", ajoUri, ajoCurrentActivity);
        }

        // Android specific methods.
        public static void OnPause()
        {
            ajcAdjust.CallStatic("onPause");
        }

        public static void OnResume()
        {
            ajcAdjust.CallStatic("onResume");
        }

        public static void SetReferrer(string referrer)
        {
            ajcAdjust.CallStatic("setReferrer", referrer, ajoCurrentActivity);
        }

        public static void GetGoogleAdId(Action<string> onDeviceIdsRead)
        {
            DeviceIdsReadListener onDeviceIdsReadProxy = new DeviceIdsReadListener(onDeviceIdsRead);
            ajcAdjust.CallStatic("getGoogleAdId", ajoCurrentActivity, onDeviceIdsReadProxy);
        }

        public static string GetAmazonAdId()
        {
            return ajcAdjust.CallStatic<string>("getAmazonAdId", ajoCurrentActivity);
        }

        // Used for testing only.
        public static void SetTestOptions(AdjustTestOptions testOptions)
        {
            AndroidJavaObject ajoTestOptions = testOptions.ToAndroidJavaObject(ajoCurrentActivity);
            ajcAdjust.CallStatic("setTestOptions", ajoTestOptions);
        }

        // Private & helper classes.
        private class AttributionChangeListener : AndroidJavaProxy
        {
            private Action<AdjustAttribution> callback;

            public AttributionChangeListener(Action<AdjustAttribution> pCallback) : base("com.adjust.sdk.OnAttributionChangedListener")
            {
                this.callback = pCallback;
            }

            // Method must be lowercase to match Android method signature.
            public void onAttributionChanged(AndroidJavaObject attribution)
            {
                if (callback == null)
                {
                    return;
                }

                AdjustAttribution adjustAttribution = new AdjustAttribution();
                adjustAttribution.trackerName = attribution.Get<string>(AdjustUtils.KeyTrackerName);
                adjustAttribution.trackerToken = attribution.Get<string>(AdjustUtils.KeyTrackerToken);
                adjustAttribution.network = attribution.Get<string>(AdjustUtils.KeyNetwork);
                adjustAttribution.campaign = attribution.Get<string>(AdjustUtils.KeyCampaign);
                adjustAttribution.adgroup = attribution.Get<string>(AdjustUtils.KeyAdgroup);
                adjustAttribution.creative = attribution.Get<string>(AdjustUtils.KeyCreative);
                adjustAttribution.clickLabel = attribution.Get<string>(AdjustUtils.KeyClickLabel);
                adjustAttribution.adid = attribution.Get<string>(AdjustUtils.KeyAdid);
                callback(adjustAttribution);
            }
        }

        private class DeferredDeeplinkListener : AndroidJavaProxy
        {
            private Action<string> callback;

            public DeferredDeeplinkListener(Action<string> pCallback) : base("com.adjust.sdk.OnDeeplinkResponseListener")
            {
                this.callback = pCallback;
            }

            // Method must be lowercase to match Android method signature.
            public bool launchReceivedDeeplink(AndroidJavaObject deeplink)
            {
                if (callback == null)
                {
                    return launchDeferredDeeplink;
                }

                string deeplinkURL = deeplink.Call<string>("toString");
                callback(deeplinkURL);
                return launchDeferredDeeplink;
            }
        }

        private class EventTrackingSucceededListener : AndroidJavaProxy
        {
            private Action<AdjustEventSuccess> callback;

            public EventTrackingSucceededListener(Action<AdjustEventSuccess> pCallback) : base("com.adjust.sdk.OnEventTrackingSucceededListener")
            {
                this.callback = pCallback;
            }

            // Method must be lowercase to match Android method signature.
            public void onFinishedEventTrackingSucceeded(AndroidJavaObject eventSuccessData)
            {
                if (callback == null)
                {
                    return;
                }
                if (eventSuccessData == null)
                {
                    return;
                }

                AdjustEventSuccess adjustEventSuccess = new AdjustEventSuccess();
                adjustEventSuccess.Adid = eventSuccessData.Get<string>(AdjustUtils.KeyAdid);
                adjustEventSuccess.Message = eventSuccessData.Get<string>(AdjustUtils.KeyMessage);
                adjustEventSuccess.Timestamp = eventSuccessData.Get<string>(AdjustUtils.KeyTimestamp);
                adjustEventSuccess.EventToken = eventSuccessData.Get<string>(AdjustUtils.KeyEventToken);
                try
                {
                    AndroidJavaObject ajoJsonResponse = eventSuccessData.Get<AndroidJavaObject>(AdjustUtils.KeyJsonResponse);
                    string jsonResponseString = ajoJsonResponse.Call<string>("toString");
                    adjustEventSuccess.BuildJsonResponseFromString(jsonResponseString);
                }
                catch (Exception)
                {
                    // JSON response reading failed.
                    // Should not be happening as of v4.12.5.
                    // Native Android SDK should send empty JSON object if none available.
                }

                callback(adjustEventSuccess);
            }
        }

        private class EventTrackingFailedListener : AndroidJavaProxy
        {
            private Action<AdjustEventFailure> callback;

            public EventTrackingFailedListener(Action<AdjustEventFailure> pCallback) : base("com.adjust.sdk.OnEventTrackingFailedListener")
            {
                this.callback = pCallback;
            }

            // Method must be lowercase to match Android method signature.
            public void onFinishedEventTrackingFailed(AndroidJavaObject eventFailureData)
            {
                if (callback == null)
                {
                    return;
                }
                if (eventFailureData == null)
                {
                    return;
                }

                AdjustEventFailure adjustEventFailure = new AdjustEventFailure();
                adjustEventFailure.Adid = eventFailureData.Get<string>(AdjustUtils.KeyAdid);
                adjustEventFailure.Message = eventFailureData.Get<string>(AdjustUtils.KeyMessage);
                adjustEventFailure.WillRetry = eventFailureData.Get<bool>(AdjustUtils.KeyWillRetry);
                adjustEventFailure.Timestamp = eventFailureData.Get<string>(AdjustUtils.KeyTimestamp);
                adjustEventFailure.EventToken = eventFailureData.Get<string>(AdjustUtils.KeyEventToken);
                try
                {
                    AndroidJavaObject ajoJsonResponse = eventFailureData.Get<AndroidJavaObject>(AdjustUtils.KeyJsonResponse);
                    string jsonResponseString = ajoJsonResponse.Call<string>("toString");
                    adjustEventFailure.BuildJsonResponseFromString(jsonResponseString);
                }
                catch (Exception)
                {
                    // JSON response reading failed.
                    // Should not be happening as of v4.12.5.
                    // Native Android SDK should send empty JSON object if none available.
                }

                callback(adjustEventFailure);
            }
        }

        private class SessionTrackingSucceededListener : AndroidJavaProxy
        {
            private Action<AdjustSessionSuccess> callback;

            public SessionTrackingSucceededListener(Action<AdjustSessionSuccess> pCallback) : base("com.adjust.sdk.OnSessionTrackingSucceededListener")
            {
                this.callback = pCallback;
            }

            // Method must be lowercase to match Android method signature.
            public void onFinishedSessionTrackingSucceeded(AndroidJavaObject sessionSuccessData)
            {
                if (callback == null)
                {
                    return;
                }
                if (sessionSuccessData == null)
                {
                    return;
                }

                AdjustSessionSuccess adjustSessionSuccess = new AdjustSessionSuccess();
                adjustSessionSuccess.Adid = sessionSuccessData.Get<string>(AdjustUtils.KeyAdid);
                adjustSessionSuccess.Message = sessionSuccessData.Get<string>(AdjustUtils.KeyMessage);
                adjustSessionSuccess.Timestamp = sessionSuccessData.Get<string>(AdjustUtils.KeyTimestamp);
                try
                {
                    AndroidJavaObject ajoJsonResponse = sessionSuccessData.Get<AndroidJavaObject>(AdjustUtils.KeyJsonResponse);
                    string jsonResponseString = ajoJsonResponse.Call<string>("toString");
                    adjustSessionSuccess.BuildJsonResponseFromString(jsonResponseString);
                }
                catch (Exception)
                {
                    // JSON response reading failed.
                    // Should not be happening as of v4.12.5.
                    // Native Android SDK should send empty JSON object if none available.
                }

                callback(adjustSessionSuccess);
            }
        }

        private class SessionTrackingFailedListener : AndroidJavaProxy
        {
            private Action<AdjustSessionFailure> callback;

            public SessionTrackingFailedListener(Action<AdjustSessionFailure> pCallback) : base("com.adjust.sdk.OnSessionTrackingFailedListener")
            {
                this.callback = pCallback;
            }

            // Method must be lowercase to match Android method signature.
            public void onFinishedSessionTrackingFailed(AndroidJavaObject sessionFailureData)
            {
                if (callback == null)
                {
                    return;
                }
                if (sessionFailureData == null)
                {
                    return;
                }

                AdjustSessionFailure adjustSessionFailure = new AdjustSessionFailure();
                adjustSessionFailure.Adid = sessionFailureData.Get<string>(AdjustUtils.KeyAdid);
                adjustSessionFailure.Message = sessionFailureData.Get<string>(AdjustUtils.KeyMessage);
                adjustSessionFailure.WillRetry = sessionFailureData.Get<bool>(AdjustUtils.KeyWillRetry);
                adjustSessionFailure.Timestamp = sessionFailureData.Get<string>(AdjustUtils.KeyTimestamp);
                try
                {
                    AndroidJavaObject ajoJsonResponse = sessionFailureData.Get<AndroidJavaObject>(AdjustUtils.KeyJsonResponse);
                    string jsonResponseString = ajoJsonResponse.Call<string>("toString");
                    adjustSessionFailure.BuildJsonResponseFromString(jsonResponseString);
                }
                catch (Exception)
                {
                    // JSON response reading failed.
                    // Should not be happening as of v4.12.5.
                    // Native Android SDK should send empty JSON object if none available.
                }

                callback(adjustSessionFailure);
            }
        }

        private class DeviceIdsReadListener : AndroidJavaProxy
        {
            private Action<string> onPlayAdIdReadCallback;

            public DeviceIdsReadListener(Action<string> pCallback) : base("com.adjust.sdk.OnDeviceIdsRead")
            {
                this.onPlayAdIdReadCallback = pCallback;
            }

            // Method must be lowercase to match Android method signature.
            public void onGoogleAdIdRead(string playAdId)
            {
                if (onPlayAdIdReadCallback == null)
                {
                    return;
                }

                this.onPlayAdIdReadCallback(playAdId);
            }

            // Handling of null object.
            public void onGoogleAdIdRead(AndroidJavaObject ajoAdId)
            {
                if (ajoAdId == null)
                {
                    string adId = null;
                    this.onGoogleAdIdRead(adId);
                    return;
                }

                this.onGoogleAdIdRead(ajoAdId.Call<string>("toString"));
            }
        }

        // Private & helper methods.
        private static bool IsAppSecretSet(AdjustConfig adjustConfig)
        {
            return adjustConfig.secretId.HasValue
            && adjustConfig.info1.HasValue
            && adjustConfig.info2.HasValue
            && adjustConfig.info3.HasValue
            && adjustConfig.info4.HasValue;
        }
    }
#endif
}


text:
package com.tle.core.taxonomy.impl;

import com.tle.core.events.ApplicationEvent;

public class TaxonomyModifiedEvent extends ApplicationEvent<TaxonomyModifiedListener> {
  private static final long serialVersionUID = 1L;

  private final String taxonomyUuid;

  public TaxonomyModifiedEvent(String taxonomyUuid) {
    super(PostTo.POST_TO_ALL_CLUSTER_NODES);
    this.taxonomyUuid = taxonomyUuid;
  }

  public String getTaxonomyUuid() {
    return taxonomyUuid;
  }

  @Override
  public Class<TaxonomyModifiedListener> getListener() {
    return TaxonomyModifiedListener.class;
  }

  @Override
  public void postEvent(TaxonomyModifiedListener listener) {
    listener.taxonomyModifiedEvent(this);
  }
}

redpajama_set_name: RedPajamaGithub


text:
package edu.buaa.sei.controller;

import edu.buaa.sei.event.IEvent;
import edu.buaa.sei.resource.ResourceContainer;

/**
 * Interface for controlling the simulation.
 * @author sei
 *
 */
public interface ISimulationController {

	boolean addContainer(ResourceContainer container);

	void addEvent(IEvent event);

	int currentTime();

	void pause();

	void resume();

	void start();

	void stop();
}


text:
<?php

// This file was auto-generated from sdk-root/src/data/ecs/2014-11-13/smoke.json
return ['version' => 1, 'defaultRegion' => 'us-west-2', 'testCases' => [['operationName' => 'ListClusters', 'input' => [], 'errorExpectedFromService' => \false], ['operationName' => 'StopTask', 'input' => ['task' => 'xxxxxxxxxxx-xxxxxxxxxxxx-xxxxxxxxxxx'], 'errorExpectedFromService' => \true]]];


text:
.class public Landroid/support/v8/renderscript/Int3;
.super Ljava/lang/Object;
.source "Int3.java"

# instance fields
.field public x:I

.field public y:I

.field public z:I

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 28
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 29
    return-void
.end method

.method public constructor <init>(III)V
    .locals 0
    .param p1, "initX"    # I
    .param p2, "initY"    # I
    .param p3, "initZ"    # I

    .prologue
    .line 31
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 32
    iput p1, p0, Landroid/support/v8/renderscript/Int3;->x:I

    .line 33
    iput p2, p0, Landroid/support/v8/renderscript/Int3;->y:I

    .line 34
    iput p3, p0, Landroid/support/v8/renderscript/Int3;->z:I

    .line 35
    return-void
.end method


text:
window.onload = function () {
    tryFindSketch();
}

function tryFindSketch () {
    var sketch = Processing.getInstanceById( getProcessingSketchId() );
    if ( sketch == undefined )
        setTimeout(tryFindSketch, 200);  // retry after 0.2 secs
    else
        sketch.setTree( document.body.parentNode );
}


text:
Spree::Shipment.class_eval do

  has_many :shipping_events, :class_name => "ShippingEvent"
  accepts_nested_attributes_for :shipping_events

  def sold_inverntory_units_count
    count = 0;
    self.inventory_units.each do |unit|
      count += 1 if unit.state = 'sold'
    end
    return count;
  end

  def backordered_inverntory_units_count
    count = 0;
    self.inventory_units.each do |unit|
      count += 1 if unit.state = 'backordered'
    end
    return count;
  end

  def send_shipment_mail
    Spree::ShipmentMailer.shipped_email(self).deliver
  end

  def partial_shipped?
    return self.shipping_events.shipped.present?
  end

  def all_shipped?
    return true if (self.shipping_events.count == self.shipping_events.shipped.count) && self.shipping_events.count != 0
    return false
  end

  def group_sold_inventory_units
    retHash = Hash.new
    self.shipping_events.un_shipped.each do |event|
      event.inventory_units.each do |unit|
        if (unit.state == "sold")
          if retHash.has_key?(unit.variant_id)
            retHash[unit.variant_id]["quantity"] += 1
          else
            retHash[unit.variant_id] = {"quantity" => 1};
          end
        end
      end
    end
    return retHash
  end

  # group the sold items from different shpping events
  def group_shipped_inventory_units
    retHash = Hash.new
    self.shipping_events.each do |event|
      if event.is_shipped?
        if retHash.has_key?(event.tracking)
          tmp = retHash[event.tracking]["units"]
          event.inventory_units.each do |unit|
            if (tmp.has_key?(unit.variant_id))
              tmp[unit.variant_id]["quantity"] += 1
            else
              tmp[unit.variant_id] = {"quantity" => 1, "sku" => unit.variant.sku, "name" => unit.variant.name_with_options_text};
            end
          end
        else
          tmp = Hash.new
          event.inventory_units.each do |unit|
            if (tmp.has_key?(unit.variant_id))
              tmp[unit.variant_id]["quantity"] += 1
            else
              tmp[unit.variant_id] = {"quantity" => 1, "sku" => unit.variant.sku, "name" => unit.variant.name_with_options_text};
            end
          end
          retHash[event.tracking] = {"tracking" => event.tracking, "shipped_at" => event.shipped_at, "carrier" => event.carrier, "units" => tmp}
        end
      end
    end
    return retHash;
  end

  def group_all_inventory_units
    retHash = Hash.new
    self.inventory_units.each do |unit|
      if retHash.has_key?(unit.variant_id)
        retHash[unit.variant_id]["quantity"] += 1
      else
        retHash[unit.variant_id] = {"quantity" => 1, "sku" => unit.variant.sku, "name" => unit.variant.name_with_options_text};
      end
    end
    return retHash;
  end

  # group the not shipped items
  def group_not_shipped_inventory_units
    retHash = Hash.new
    self.inventory_units.each do |unit|
      if unit.state == 'sold' || unit.state == 'backordered'
        if retHash.has_key?(unit.variant_id)
          retHash[unit.variant_id]["quantity"] += 1
        else
          retHash[unit.variant_id] = {"quantity" => 1, "sku" => unit.variant.sku, "name" => unit.variant.name_with_options_text};
        end
      end
    end
    return retHash;
  end

  def create_shipping_events()
    # sold = sold_inverntory_units_count;
    # backordered = backordered_inverntory_units_count;

    shipping_events.delete_all

    #se_sold = ShippingEvent.new
    #sold_collections = Array.new;

    self.inventory_units.each do |unit|

        se = ShippingEvent.new
        se.shipment = self
        #se_backordered.inventory_units = Array.new.push(InventoryShippingEvent.build(unit))
        se.inventory_units = Array.new.push(unit)
        se.save

      # if (unit.state == 'sold')
      #   #sold_collections.push(InventoryShippingEvent.build(unit))
      #   sold_collections.push(unit)
      # elsif (unit.state == 'backordered')
      #   se_backordered = ShippingEvent.new
      #   se_backordered.shipment = self
      #   #se_backordered.inventory_units = Array.new.push(InventoryShippingEvent.build(unit))
      #   se_backordered.inventory_units = Array.new.push(unit)
      #   se_backordered.save
      # end
    end

    # if (sold_collections.size > 0)
    #     se_sold = ShippingEvent.new
    #     se_sold.shipment = self
    #     se_sold.inventory_units = sold_collections
    #     se_sold.save
    # end

  end

  def shipment_statement
    if (self.all_shipped?)
      return "shipped"
    else
      return "partially shipped"
    end
  end

  def set_tracking_number
    self.shipping_events do |event|
      if self.tracking.blank?
        self.tracking = event.tracking
      else
        self.tracking = self.tracking + "," + event.tracking
      end
    end
  end
  # def valid_address()
  #   return true if self.address_id == self.order.ship_address_id
  #   return true
  # end

  # doing nothing after shipping
  def after_ship
    # ShipmentMailer.shipped_email(self).deliver
  end

    # backorder = order.backordered_inverntory_units_count;
    # return if backorder == 0
    #
    # sold = order.sold_inverntory_units_count;
    # return if sold == 0 && backorder == 1
    #
    # if sold == 0
    #   skip_first = true
    # else
    #   skip_first = false
    # end
    # icount = 0;
    # order.inventory_units.backorder.each do |unit|
    #   if icount > 0 || !skip_first
    #     shipment = build_shipment(order)
    #     shipment.cost = 0;
    #     shipment.inventory_unit_ids = Array.new.push(unit.id)
    #     shipment.save
    #   end
    #   icount += 1;
    # end

    # Updates various aspects of the Shipment while bypassing any callbacks.  Note that this method takes an explicit reference to the
    # Order object.  This is necessary because the association actually has a stale (and unsaved) copy of the Order and so it will not
    # yield the correct results.
    # def update!(order)
    #
    #   old_state = self.state
    #   Rails.logger.info("1RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR1:" + old_state)
    #   new_state = determine_state(order)
    #   Rails.logger.info("1RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR2:" + new_state)
    #   update_attribute_without_callbacks 'state', determine_state(order)
    #   after_ship if new_state == 'shipped' and old_state != 'shipped'
    # end

end


text:
'use strict';

var session = require('express-session');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var express = require('express');
var morgan = require('morgan');
var path = require('path');
var consolidate = require('consolidate');

module.exports = function(Config) {
  var port = Config.port;
  var app = express();
  app.set('port', port);
  app.set('views', __dirname + '/../views');
  app.set('view engine', 'html');
  app.engine('html', consolidate.swig);
  app.set('view options', {
    layout: false
  });
  app.use(morgan({ format: 'dev', immediate: true }));
  app.use(bodyParser());
  app.use(require('errorhandler')());
  app.use(require('method-override')());
  app.use(cookieParser('F;;v,m-{-HC6YqTR}T=;'));
  app.use(session({
    cookie: { maxAge: 365 * 24 * 60 * 60 * 1000 },
    secret: 'HaTuBqJFsX92ngYZqEKR'
  }));

  app.use(express.static(path.join(__dirname, '../public')));

  app.listen(port, function() {
    return console.log('Listening on ' + port);
  });

  return app;
};


text:
package main_test

import (
	"bytes"
	"errors"
	"fmt"
	"github.com/fgrosse/goldi/goldigen"
	. "github.com/fgrosse/gomega-matchers"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"strings"
)

type errorReader struct{}

func (errorReader) Read(p []byte) (n int, err error) {
	return 0, errors.New("error from errorReader")
}

var _ = Describe("Generator", func() {
	var (
		gen               *main.Generator
		output            *bytes.Buffer
		inputPath         = "/absolute/path/conf/servo_types.yml"
		outputPath        = "/absolute/path/servo_types.go"
		outputPackageName = "github.com/fgrosse/some/thing"
		exampleYaml       = `
			types:
				goldi.test.foo:
					package: github.com/fgrosse/some/thing
					type:    Foo
					factory: NewFoo

				graphigo.client:
					package: github.com/fgrosse/graphigo
					type:    Graphigo
					factory: NewClient

				simple.struct:
					package: github.com/fgrosse/servo/example
					type:    MyStruct

				http_handler:
					package: github.com/fgrosse/servo/example
					func:    HandleHTTP

				logger:
					package: github.com/mgutz/logxi.v1
					package-name: log
					type:    Logger
					factory: New
					arguments: [ test ]
		`
	)

	BeforeEach(func() {
		config := main.NewConfig(outputPackageName, "RegisterTypes", inputPath, outputPath)
		gen = main.NewGenerator(config)
		output = &bytes.Buffer{}
	})

	It("should return error for invalid definition", func() {
		yaml := `
			types:
				goldi.test.foo:
					package: test
					factory: @foo_provider::NewFoo
					args:
						invalid yml`

		err := gen.Generate(strings.NewReader(yaml), output)
		Expect(err).To(HaveOccurred())
		Expect(err.Error()).To(HavePrefix("could not parse type definition: yaml: unmarshal errors:"))
	})

	It("should return error when cannot read from input", func() {
		Expect(gen.Generate(errorReader{}, output)).To(MatchError("could not parse type definition: error from errorReader"))
	})

	It("should not be necessary to quote type references because of the @", func() {
		// the @ has some special significance in yaml which we are going to ignore in goldigen
		yaml := `
			types:
				goldi.test.foo:
					package: test
					factory: @foo_provider::NewFoo
					args:
						- @bar
						- john.doe@example.com
						- 'alice@example.com'
						- "mallory@example.com"
						- There is an @ here
						- 1`

		Expect(gen.Generate(strings.NewReader(yaml), output)).To(Succeed())
		Expect(output).To(ContainCode(`
			func RegisterTypes(types goldi.TypeRegistry) {
				types.Register("goldi.test.foo", goldi.NewProxyType("foo_provider", "NewFoo", "@bar", "john.doe@example.com", "alice@example.com", "mallory@example.com", "There is an @ here", 1))
			}
		`))
	})

	It("should generate valid go code", func() {
		Expect(gen.Generate(strings.NewReader(exampleYaml), output)).To(Succeed())
		Expect(output).To(BeValidGoCode())
	})

	It("should use the given package name", func() {
		Expect(gen.Generate(strings.NewReader(exampleYaml), output)).To(Succeed())
		Expect(output).To(DeclarePackage("thing"))
	})

	Describe("generating import statements", func() {
		BeforeEach(func() {
			Expect(gen.Generate(strings.NewReader(exampleYaml), output)).To(Succeed())
			Expect(output).To(BeValidGoCode())
		})

		It("should import the goldi package", func() {
			Expect(output).To(ImportPackage("github.com/fgrosse/goldi"))
		})

		It("should import the type packages", func() {
			Expect(output).To(ImportPackage("github.com/fgrosse/graphigo"))
		})

		It("should not import the output package", func() {
			Expect(output).NotTo(ImportPackage(outputPackageName))
		})

		It("should not import type packages multuple times", func() {
			Expect(output).To(ImportPackage("github.com/fgrosse/servo/example"))
		})

		It("should import packages that contain a version", func() {
			Expect(output).To(ImportPackage("github.com/mgutz/logxi.v1"))
		})
	})

	It("should define the types in a global function", func() {
		Expect(gen.Generate(strings.NewReader(exampleYaml), output)).To(Succeed())
		// Note that NewFoo has no explicit package name since it is defined within the given outputPackageName
		Expect(output).To(ContainCode(`
			func RegisterTypes(types goldi.TypeRegistry) {
				types.RegisterAll(map[string]goldi.TypeFactory{
					"goldi.test.foo":  goldi.NewType(NewFoo),
					"graphigo.client": goldi.NewType(graphigo.NewClient),
					"http_handler":    goldi.NewFuncType(example.HandleHTTP),
					"logger":          goldi.NewType(log.New, "test"),
					"simple.struct":   goldi.NewStructType(new(example.MyStruct)),
				})
			}
		`))
	})

	Context("with parameters", func() {
		BeforeEach(func() {
			exampleYaml = `
			parameters:
				graphigo.base_url: https://example.com/graphigo:8443

			types:
				graphigo.client:
					package: github.com/fgrosse/graphigo
					type:    Graphigo
					factory: NewClient
					arguments:
						- "%graphigo.base_url%"
						- 100
		`
		})

		It("should define the types in a global function", func() {
			Expect(gen.Generate(strings.NewReader(exampleYaml), output)).To(Succeed())
			Expect(output).To(ContainCode(`
				func RegisterTypes(types goldi.TypeRegistry) {
					types.Register("graphigo.client", goldi.NewType(graphigo.NewClient, "%graphigo.base_url%", 100))
				}
			`))
		})
	})

	It("should validate the input", func() {
		invalidInput := `
			types:
				ok:
					package: some/package
					factory: NewFoo

				bad:
					type: TypeRegistry
					factory: NewTypeRegistry
		`
		Expect(gen.Generate(strings.NewReader(invalidInput), output)).
			To(MatchError(`type definition of "bad" is missing the required "package" key`))
	})

	It("should not replace tab characters in the middle of any value", func() {
		input := fmt.Sprintf(`
			types:
				test:
					package: foo/bar
					factory: NewFoo
					arguments:
            			- "%s"
		`, "Hello\t\t\tWorld")
		Expect(gen.Generate(strings.NewReader(input), output)).To(Succeed())
		Expect(output).To(ContainCode(fmt.Sprintf(`
			func RegisterTypes(types goldi.TypeRegistry) {
				types.Register("test", goldi.NewType(bar.NewFoo, "%s"))
			}
		`, "Hello\t\t\tWorld")))
	})

	It("should include the go generate code which was used to create this file", func() {
		Expect(gen.Generate(strings.NewReader(exampleYaml), output)).To(Succeed())
		Expect(output).To(ContainCode(fmt.Sprintf(
			`//go:generate goldigen --in "conf/servo_types.yml" --out "servo_types.go" --package %s --function RegisterTypes --overwrite --nointeraction`,
			outputPackageName,
		)))
	})

	It("should allow specifying configuration types", func() {
		input := `
			types:
				test:
					package: foo/bar
					factory: NewFoo
					configurator: ["@confoogurator", Configure]
		`
		Expect(gen.Generate(strings.NewReader(input), output)).To(Succeed())
		Expect(output).To(ContainCode(`
			func RegisterTypes(types goldi.TypeRegistry) {
				types.Register("test", goldi.NewConfiguredType(
					goldi.NewType(bar.NewFoo),
					"confoogurator", "Configure",
				))
			}
		`))
	})

	It("should log message in debug mode", func() {
		logger := new(bytes.Buffer)
		gen.Debug = true
		gen.Logger = logger
		gen.Generate(strings.NewReader(exampleYaml), output)
		Expect(logger.String()).NotTo(BeEmpty())
		gen.Debug = false
	})

})


text:
import logging

from google.appengine.api import app_identity
from google.appengine.ext import db

from mcfw.cache import CachedModelMixIn, cached
from mcfw.rpc import returns, arguments
from mcfw.serialization import deserializer, ds_model, serializer, s_model, register
from mcfw.utils import chunks
from rogerthat.models.utils import add_meta

class ServerSettings(CachedModelMixIn, db.Model):
    messageFlowRunnerAddress = add_meta(db.StringProperty(indexed=False),
                                        doc="Message flow runner address",
                                        order=5)
    mobidickAddress = add_meta(db.StringProperty(indexed=False),
                               doc="Mobidick address:",
                               order=5)
    secret = add_meta(db.StringProperty(indexed=False),
                      doc="Server secret",
                      order=5)
    baseUrl = add_meta(db.StringProperty(indexed=False),
                       doc="Rogerthat cloud address",
                       order=5)
    webClientUrl = add_meta(db.StringProperty(indexed=False),
                       doc='Web client url',
                       order=6)
    jabberDomain = add_meta(db.StringProperty(indexed=False),
                            doc="Jabber domain",
                            order=10)
    jabberSecret = add_meta(db.StringProperty(indexed=False),
                            doc="Jabber secret",
                            order=10)
    jabberAccountEndPoints = add_meta(db.StringListProperty(indexed=False),
                                      doc="Jabber account endpoints (one ip/port combination per port. eg: 192.168.10.23:8001)",
                                      order=10)
    jabberEndPoints = add_meta(db.StringListProperty(indexed=False),
                               doc="Jabber endpoints (one ip/port combination per port. eg: 192.168.10.23:8001)",
                               order=10)
    jabberBoshEndPoint = add_meta(db.StringProperty(indexed=False),
                                  doc="Jabber bosh endpoint",
                                  order=10)
    dashboardEmail = add_meta(db.StringProperty(indexed=False),
                              doc="Dashboard e-mail address",
                              order=5)
    brandingRendererUrl = add_meta(db.StringProperty(indexed=False),
                                   doc="Branding renderer address",
                                   order=5)
    srvEndPoints = add_meta(db.StringListProperty(indexed=False),
                            doc="DNS SRV records (ip:port:priority. eg: 192.168.10.23:5222:0)",
                            order=11)
    newsServerEndpoints = add_meta(db.StringListProperty(indexed=False),
                                   doc='Used to send realtime updates of news items to the (mobile) clients. records (ip:port)',
                                   order=12)
    newsServerWebhookEndpoint = add_meta(db.StringProperty(indexed=False),
                                         doc='Used to send updates to the news update server (https?://ip:port)',
                                         order=13)
    smtpserverHost = add_meta(db.StringProperty(indexed=False),
                              order=30)
    smtpserverPort = add_meta(db.StringProperty(indexed=False),
                              order=30)
    smtpserverLogin = add_meta(db.StringProperty(indexed=False),
                               order=30)
    smtpserverPassword = add_meta(db.StringProperty(indexed=False),
                                  order=30)
    dkimPrivateKey = add_meta(db.TextProperty(indexed=False),
                              doc="DKIM private key",
                              order=40)
    sendGridApiKey = add_meta(db.TextProperty(indexed=False),
                              doc="SendGrid api key",
                              order=41)

    firebaseKey = add_meta(db.StringProperty(indexed=False), doc="Firebase Cloud Messaging API Key", order=60)
    gcmKey = add_meta(db.StringProperty(indexed=False), doc="Google Cloud Messaging Key", order=61)
    googleMapsKey = add_meta(db.StringProperty(indexed=False), doc="Google Maps Key", order=62)
    googleMapsUrlSigningSecret = add_meta(db.StringProperty(indexed=False), doc='Google Maps Url signing secret. See https://console.cloud.google.com/google/maps-apis/credentials', order=63)

    registrationMainSignature = add_meta(db.StringProperty(indexed=False),
                                         doc="baee64 version of main registration signature", order=80)
    emailHashEncryptionKey = add_meta(db.StringProperty(indexed=False),
                                          doc='Email hash encryption key. Only used for creating apps. No idea why this is needed.',
                                          order=80)
    registrationEmailSignature = add_meta(db.StringProperty(indexed=False),
                                          doc="baee64 version of email registration signature", order=81)
    registrationPinSignature = add_meta(db.StringProperty(indexed=False),
                                        doc="baee64 version of pin registration signature", order=82)

    userCodeCipher = add_meta(db.StringProperty(indexed=False),
                              doc="UserCode cipher (base64.b64encode(SECRET_KEY).decode('utf-8')) and should contain a %s",
                              order=83)

    userEncryptCipherPart1 = add_meta(db.StringProperty(indexed=False),
                                      doc="User encrypt cipher part 1 (base64.b64encode(SECRET_KEY).decode('utf-8'))",
                                      order=84)
    userEncryptCipherPart2 = add_meta(db.StringProperty(indexed=False),
                                      doc="User encrypt cipher part 2 (base64.b64encode(SECRET_KEY).decode('utf-8'))",
                                      order=85)
    cookieSecretKey = add_meta(db.StringProperty(indexed=False),
                               doc="Secret key to encrypt the session (base64.b64encode(SECRET_KEY).decode('utf-8'))",
                               order=86)
    cookieSessionName = add_meta(db.StringProperty(indexed=False), doc="Cookie name for the session", order=87)
    cookieQRScanName = add_meta(db.StringProperty(indexed=False), doc="Cookie name for qr codes", order=88)

    supportEmail = add_meta(db.StringProperty(indexed=False), doc="Main email address to contact support", order=89)
    supportWorkers = add_meta(db.StringListProperty(indexed=False),
                              order=90)

    staticPinCodes = add_meta(db.StringListProperty(indexed=False),
                              doc="Static pin codes  (2 entries per combination. eg: - pincode - test@example.com)",
                              order=93)

    ysaaaMapping = add_meta(db.StringListProperty(indexed=False),
                            doc="YSAAA mapping  (2 entries per combination. eg: - hash - test@example.com)",
                            order=94)

    signupUrl = add_meta(db.StringProperty(indexed=False),
                         doc="Signup URL (e.g. https://example.com/signup)",
                         order=100)
    customSigninPaths = add_meta(db.StringListProperty(indexed=False),
                                 doc="Custom sign in paths based on host name (2 entries per combination. eg: - dashboard.example.com - /user/signin",
                                 order=101)

    firebaseApiKey = add_meta(db.StringProperty(indexed=False),
                              doc='Firebase api key',
                              order=200)
    firebaseAuthDomain = add_meta(db.StringProperty(indexed=False),
                                  doc='Firebase auth domain',
                                  order=201)
    firebaseDatabaseUrl = add_meta(db.StringProperty(indexed=False),
                                   doc='Firebase database URL',
                                   order=202)

    news_statistics_influxdb_host = add_meta(db.StringProperty(indexed=False),
                                             doc='News stats influxdb HOST',
                                             order=301)
    news_statistics_influxdb_port = add_meta(db.IntegerProperty(indexed=False),
                                             doc='News stats influxdb PORT',
                                             order=302)
    news_statistics_influxdb_username = add_meta(db.StringProperty(indexed=False),
                                                 doc='News stats influxdb USER',
                                                 order=304)
    news_statistics_influxdb_password = add_meta(db.StringProperty(indexed=False),
                                                 doc='News stats influxdb PWD',
                                                 order=305)
    news_admin_emails = add_meta(db.StringListProperty(indexed=False),
                                 doc="The email addresses that have admin access to the news dashboard",
                                 order=307)

    mobileFirebaseCredentials = add_meta(db.TextProperty(),
                                         doc='Credentials json file for firebase storage on android and ios',
                                         order=400)

    oca3ApiKey = add_meta(db.StringProperty(indexed=False),
                                            doc='oca-dot-rogerthat-server.ew.r.appspot.com/api api key',
                                            order=501)

    imageResizerApiKey = add_meta(db.StringProperty(indexed=False),
                                            doc='imageresizer-dot-rogerthat-server.ew.r.appspot.com/api api key',
                                            order=502)

    @property
    def senderEmail(self):
        return "Rogerthat Dashboard <%s>" % self.dashboardEmail

    @property
    def senderEmail2ToBeReplaced(self):
        return "Rogerthat Dashboard <rogerthat@%s.appspotmail.com>" % app_identity.get_application_id()

    @property
    def domain(self):
        return self.jabberDomain

    def invalidateCache(self):
        logging.info("ServerSettings removed from cache.")
        get_server_settings.invalidate_cache()

    def get_signin_url(self):
        for url, path in chunks(self.customSigninPaths, 2):
            if path.startswith('/customers/signin'):
                return 'https://%s%s' % (url, path)
        return self.baseUrl

@deserializer
def ds_ss(stream):
    return ds_model(stream, ServerSettings)

@serializer
def s_ss(stream, server_settings):
    s_model(stream, server_settings, ServerSettings)

register(ServerSettings, s_ss, ds_ss)

@cached(1, 3600, read_cache_in_transaction=True)
@returns(ServerSettings)
@arguments()
def get_server_settings():
    # type: () -> ServerSettings
    @db.non_transactional
    def get():
        ss = ServerSettings.get_by_key_name("MainSettings")
        if not ss:
            ss = ServerSettings(key_name="MainSettings")
        return ss

    return get()

del ds_ss
del s_ss


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="../jsp/xmlverbatimwrapper.xsl"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0" xmlns:xlink="http://www.w3.org/1999/xlink"
 xmlns:mml="http://www.w3.org/1998/Math/MathML">
	<!-- Inst. of Appl. Phys., Acad. of Sci., Nizhny Novgorod; -->
    <teiHeader xml:lang="en">
		<fileDesc>
			<sourceDesc>
				<biblStruct>
					<analytic>
						<author>
							<affiliation>
								<orgName type="department">Inst. of Appl. Phys.</orgName>,
								<orgName type="institution">Acad. of Sci.</orgName>,
								<address>
                                    <settlement>Nizhny Novgorod</settlement>;
								</address>
							</affiliation>
						</author>
					</analytic>
				</biblStruct>
			</sourceDesc>
		</fileDesc>
	</teiHeader>
</TEI>


text:
package com.haibin.qiaqia.fruitvegetables;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.haibin.qiaqia.R;

/**
 * Created by invinjun on 2016/7/3.
 */
@SuppressLint("ValidFragment")
public class SimpleCardFragment extends Fragment {
    private String mTitle;

    public static SimpleCardFragment getInstance(String title) {
        SimpleCardFragment sf = new SimpleCardFragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fr_simple_card, null);
        TextView card_title_tv = (TextView) v.findViewById(R.id.card_title_tv);
        card_title_tv.setText(mTitle);

        return v;
    }
}


text:
<?php

namespace AppBundle\Factory\Common\Choices\Bool;

use AppBundle\Factory\Common\Choices\Base\SimpleChoicesFactory;
use AppBundle\Filter\Base\Filter;

class InfoproduktChoicesFactory extends SimpleChoicesFactory {

	public function __construct() {
		$this->items['label.all'] = Filter::ALL_VALUES;
		$this->items['label.infoprodukt'] = Filter::TRUE_VALUES;
		$this->items['label.notInfoprodukt'] = Filter::FALSE_VALUES;
	}
}


text:
hljs.registerLanguage("flix",(()=>{"use strict";return e=>({name:"Flix",
keywords:{literal:"true false",
keyword:"case class def else enum if impl import in lat rel index let match namespace switch type yield with"
},contains:[e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE,{className:"string",
begin:/'(.|\\[xXuU][a-zA-Z0-9]+)'/},{className:"string",variants:[{begin:'"',
end:'"'}]},{className:"function",beginKeywords:"def",end:/[:={\[(\n;]/,
excludeEnd:!0,contains:[{className:"title",relevance:0,
begin:/[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/
}]},e.C_NUMBER_MODE]})})());


text:
package org.apache.camel.component.stream;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.junit.Test;

/**
 * Unit test for delay option.
 */
public class StreamDelayTest extends CamelTestSupport {

    @Test
    public void testStringContent() throws Exception {
        long start = System.currentTimeMillis();
        template.sendBody("direct:in", "Hello Text World\n");
        long delta = System.currentTimeMillis() - start;
        assertTrue("Delay should be around 2 sec: " + delta, delta > 1900 && delta < 3000);
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            public void configure() {
                from("direct:in").to("stream:out?delay=2000");
            }
        };
    }

}


text:
from decimal import Decimal
from django.db import migrations, models
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
        ("checkout", "0049_auto_20220621_0850"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="checkout",
            options={
                "ordering": ("-last_change", "pk"),
                "permissions": (
                    ("manage_checkouts", "Manage checkouts"),
                    ("handle_checkouts", "Handle checkouts"),
                    ("handle_taxes", "Handle taxes"),
                ),
            },
        ),
        migrations.AddField(
            model_name="checkout",
            name="price_expiration",
            field=models.DateTimeField(default=django.utils.timezone.now),
        ),
        migrations.AddField(
            model_name="checkout",
            name="shipping_price_gross_amount",
            field=models.DecimalField(
                decimal_places=3, default=Decimal("0"), max_digits=12
            ),
        ),
        migrations.AddField(
            model_name="checkout",
            name="shipping_price_net_amount",
            field=models.DecimalField(
                decimal_places=3, default=Decimal("0"), max_digits=12
            ),
        ),
        migrations.AddField(
            model_name="checkout",
            name="shipping_tax_rate",
            field=models.DecimalField(
                decimal_places=4, default=Decimal("0.0"), max_digits=5
            ),
        ),
        migrations.AddField(
            model_name="checkout",
            name="subtotal_gross_amount",
            field=models.DecimalField(
                decimal_places=3, default=Decimal("0"), max_digits=12
            ),
        ),
        migrations.AddField(
            model_name="checkout",
            name="subtotal_net_amount",
            field=models.DecimalField(
                decimal_places=3, default=Decimal("0"), max_digits=12
            ),
        ),
        migrations.AddField(
            model_name="checkout",
            name="total_gross_amount",
            field=models.DecimalField(
                decimal_places=3, default=Decimal("0"), max_digits=12
            ),
        ),
        migrations.AddField(
            model_name="checkout",
            name="total_net_amount",
            field=models.DecimalField(
                decimal_places=3, default=Decimal("0"), max_digits=12
            ),
        ),
        migrations.AddField(
            model_name="checkoutline",
            name="currency",
            field=models.CharField(max_length=3, null=True),
        ),
        migrations.AddField(
            model_name="checkoutline",
            name="tax_rate",
            field=models.DecimalField(
                decimal_places=4, default=Decimal("0.0"), max_digits=5
            ),
        ),
        migrations.AddField(
            model_name="checkoutline",
            name="total_price_gross_amount",
            field=models.DecimalField(
                decimal_places=3, default=Decimal("0"), max_digits=12
            ),
        ),
        migrations.AddField(
            model_name="checkoutline",
            name="total_price_net_amount",
            field=models.DecimalField(
                decimal_places=3, default=Decimal("0"), max_digits=12
            ),
        ),
    ]


text:
cask 'remote-desktop-manager' do
  version '4.4.2.0'
  sha256 '49b833f23f5a88d1ba6ab84ac1967044d0423f233f843e08bddd1e376189cca8'

  # devolutions.net was verified as official when first introduced to the cask
  url "http://cdn.devolutions.net/download/Mac/Devolutions.RemoteDesktopManager.Mac.#{version}.dmg"
  appcast 'http://cdn.devolutions.net/download/Mac/RemoteDesktopManager.xml',
          checkpoint: 'd28958f114906feb9433ca50cc6d9d037340d5c75bf8b969dc73c6508513e4bf'
  name 'Remote Desktop Manager'
  homepage 'https://mac.remotedesktopmanager.com/'

  app 'Remote Desktop Manager.app'
end


text:
budget_alg=154
graph_compression='../../../graph_compression'
num_threads=8
data_file='traffic_5328'
param_budget=(77 154 308 616 1231 2462)
results_sse_reduction="traffic_sse_reduction_budget"


text:
megabyte=$((10**6))
gigabyte=$((10**9))
# Set this factor for overbooking and/or to account
# for some inaccuracy in data metering
quota_factor="107/100"
# Quota distributed to each user on the 1. day
start_quota=$((500*megabyte))
# Cap for free amount of data each user can save. Everything above will
# distributed evenly among all users.
maximal_savings=$((1300*megabyte))
# Days before end of month the cap for free amount of data is reduced.
# This helps to give all users (and especially power users) the possibility to
# use all data provided by the tarif
start_maximum_lowering=8
# Lower maximal saving linearly to
lowest_maximum=$((200*megabyte))
# Stop distribution of free data.
stop_distribution_days_before=1

## Users

nusers=2
user1="Bob"; iprange1="192.168.1.60-192.168.1.69"; monthly_quota1=$((10*gigabyte))
user2="Alice"; iprange2="192.168.1.50-192.168.1.59"; monthly_quota2=$((20*gigabyte))

## Mail settings

mailsmtp="imap.example.de"
mailuser="gargoyle@example.com"
mailpassword="passphrase"
mailsender="gargoyle@example.com"
recipientshourly="your@mail.com"


text:
<dataConfig>
  <document>
    <entity name="provider" pk="id" dataSource="rw_db" onError="skip"
        query="
SELECT id,
       vendor_id,
       external_id,
       name,
       description,
       email,
       status,
       min_cost,
       max_cost,
       created_date,
       last_modified_date,
       service_address_id
  FROM provider
 WHERE status != 0
"
        deltaQuery="
SELECT PRO.id
  FROM provider PRO,
       vendor VE
 WHERE PRO.vendor_id=VE.id
   AND PRO.status != 0
   AND (
       PRO.last_modified_date > DATE_SUB('${dataimporter.last_index_time}', INTERVAL 1 MINUTE)
       OR
       VE.last_modified_date > DATE_SUB('${dataimporter.last_index_time}', INTERVAL 1 MINUTE)
       )
"
        deltaImportQuery="
SELECT id,
       vendor_id,
       external_id,
       name,
       description,
       email,
       status,
       min_cost,
       max_cost,
       created_date,
       last_modified_date,
       service_address_id
  FROM provider
 WHERE id='${dataimporter.delta.id}'
"
        deletedPkQuery="
SELECT id
  FROM provider
 WHERE status = 0
   AND last_modified_date > DATE_SUB('${dataimporter.last_index_time}', INTERVAL 1 MINUTE)
">

      <field column="id" name="id"/>
      <field column="vendor_id" name="vendor_id"/>
      <field column="external_id" name="external_id"/>
      <field column="name" name="name"/>
      <field column="description" name="description"/>
      <field column="email" name="email"/>
      <field column="status" name="status"/>
      <field column="created_date" name="created_date"/>
      <field column="last_modified_date" name="last_modified_date"/>
      <field column="min_cost" name="min_cost"/>
      <field column="max_cost" name="min_cost"/>

      <entity name="activity_option_values" dataSource="rw_db" query="SELECT DISTINCT(PO.name) AS option_name FROM provider PR JOIN activity AC ON PR.id = AC.provider_id JOIN activity_option AO ON AC.id = AO.activity_id JOIN provider_option PO ON PO.id = AO.option_id WHERE PR.id  = '${provider.id}'">
        <field column="option_name" name="activity_option_values"/>
      </entity>

      <entity name="leaf_categories" dataSource="rw_db" query="SELECT distinct(CAT.parent_id) AS top_level_category_ids, PARENT_CAT.name AS top_level_category_names, CAT.id AS leaf_category_ids, CAT.name AS leaf_category_names FROM category AS CAT JOIN provider_categories AS PC ON CAT.id=PC.category_id JOIN provider AS PRO ON PC.provider_id=PRO.id JOIN category AS PARENT_CAT ON CAT.parent_id=PARENT_CAT.id WHERE PRO.id='${provider.id}' AND CAT.depth=2 AND PARENT_CAT.id=CAT.parent_id">
        <field column="leaf_category_ids" name="leaf_category_ids"/>
        <field column="leaf_category_names" name="leaf_category_names"/>
        <field column="top_level_category_ids" name="top_level_category_ids"/>
        <field column="top_level_category_names" name="top_level_category_names"/>
      </entity>

      <entity name="vendor" dataSource="rw_db" query="SELECT IF(PRO.booking_method IS NOT NULL, PRO.booking_method, VE.booking_method) AS booking_method FROM provider AS PRO JOIN vendor AS VE ON PRO.vendor_id=VE.id WHERE PRO.id='${provider.id}'">
        <field column="booking_method" name="booking_method"/>
      </entity>

      <entity name="provider_loc" dataSource="rw_db" query="SELECT ADDR.city AS city, ADDR.address_state AS state, ADDR.zip_code AS zip_code, CONCAT(ADDR.latitude,',',ADDR.longitude) AS coordinates FROM service_address AS ADDR WHERE ADDR.id='${provider.service_address_id}' AND ADDR.latitude IS NOT NULL AND ADDR.longitude IS NOT NULL">
        <field column="city" name="city"/>
        <field column="state" name="state"/>
        <field column="zip_code" name="zip_code"/>
        <field column="coordinates" name="coordinates"/>
      </entity>

    </entity>
  </document>
</dataConfig>


text:
package net.strongdesign.desij.decomposition.partitioning;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Collection;

import net.strongdesign.stg.STG;
import net.strongdesign.stg.STGException;
import net.strongdesign.stg.Signature;
import net.strongdesign.stg.traversal.Condition;

/**
 * @author Dominic Wist
 *
 */
public class CSCPartition {

	private Map<Integer,STG> output2Component;
	private Map<STG,Set<Integer>> component2Outputs;

	// for building the resulting partition:
	// Which components will be consolidated?
	private Map<STG,Set<STG>> component2Components;

	// abort condition for consolidating components
	private Condition<Collection<STG>> forbidConsolitionCondition;

	// information used by a combined partitioning heuristic
	// a true entry means compatible and no entry (i.e. null) means not compatible
	// for each compatible pair: there will always be both symmetric entries
	private Map<STG,Map<STG,Boolean>> compatibilityChart;

	public CSCPartition(Collection<STG> components, Condition<Collection<STG>> forbidConsolidation) {

		component2Outputs = new HashMap<STG, Set<Integer>>(components.size());
		output2Component = new HashMap<Integer, STG>();

		component2Components = new HashMap<STG, Set<STG>>(components.size());

		Set<Integer> compOutputs;
		Set<STG> stgSet;
		for (STG comp : components) {
			compOutputs = comp.getSignals(Signature.OUTPUT);
			component2Outputs.put(comp, compOutputs);

			for (Integer output : compOutputs)
				output2Component.put(output, comp);

			stgSet = new HashSet<STG>();
			stgSet.add(comp);
			component2Components.put(comp, stgSet);
		}

		forbidConsolitionCondition = forbidConsolidation;

		compatibilityChart = new HashMap<STG, Map<STG,Boolean>>();
	}

	public boolean useSignalForComponent(Integer output, STG component) {

		STG auxiliaryComponent = output2Component.get(output);

		setCompatibilty(component, auxiliaryComponent); // information used by a combined heuristic

		if (auxiliaryComponent == component) return true; // should be impossible, actually

		Set<STG> componentConsolidationSet =
			new HashSet<STG>(component2Components.get(component));
		componentConsolidationSet.addAll(component2Components.get(auxiliaryComponent));

		// Is this component consolidation allowed?
		if ( forbidConsolitionCondition.fulfilled(componentConsolidationSet) )
			return false; // no component consolidation --> conflict can not be avoided

		// update all necessary entries in component2Components
		for (STG comp : componentConsolidationSet)
			component2Components.put(comp, componentConsolidationSet);

		return true;
	}

	/**
	 * Ensures the consistency of compatibilityChart
	 * that means for one compatible pair there are two symmetric entries
	 *
	 * @param component
	 * @param auxiliaryComponent
	 */
	private void setCompatibilty(STG component, STG auxiliaryComponent) {

		// first entry
		Map<STG, Boolean> entry = compatibilityChart.get(component);
		if (entry == null) {
			entry = new HashMap<STG, Boolean>();
			compatibilityChart.put(component, entry);
		}
 		entry.put(auxiliaryComponent, true);

		// symmetric entry
 		entry = compatibilityChart.get(auxiliaryComponent);
 		if (entry == null) { // must correlate to "if (entry == null)" from above
			entry = new HashMap<STG, Boolean>();
			compatibilityChart.put(auxiliaryComponent, entry);

 		}
 		entry.put(component, true);

	}

	/**
	 * Information whether component1 and component2 are in a "critical <--> delay component"-relation
	 * it is for PartitionerIrreducibleCSCAvoidance
	 *
	 * @param output1
	 * @param output2
	 * @return
	 */
	public boolean getCompatibility(int output1, int output2) {

		STG component1 = output2Component.get(output1); // according to the oldPartition
		STG component2 = output2Component.get(output2); // according to the oldPartition

		if (component1 == component2) return true; // actually impossible --> just to assure

		Map<STG,Boolean> firstLevelAccess = compatibilityChart.get(component1);
		if (firstLevelAccess != null)
			if (firstLevelAccess.get(component2) != null)
				return true;

		return false;
	}

	/**
	 * Helper routine for delay transition detector
	 * @param output
	 * @param component
	 * @return
	 */
	public boolean signalAvoidsComponentGrowth(Integer output, STG component) {

		Set<STG> consolidatedComponents = component2Components.get(component);
		STG auxiliaryComponent = output2Component.get(output);

		// output is already in the resulting partition
		if (consolidatedComponents.contains(auxiliaryComponent))
			return true;
		else
			return false;

	}

	public Partition getModifiedPartitionFor(STG specification) throws STGException {

		// the construction of a new set is necessary to avoid repetitions in allConsolidatedComponents
		Set<Set<STG>> allConsolidatedComponents =
			new HashSet<Set<STG>>(component2Components.values());

		Partition newPartition = new Partition();

		for (Set<STG> consolidatedComponents: allConsolidatedComponents) {
			newPartition.beginSignalSet();
			for (STG component: consolidatedComponents)
				for (Integer compOutput : component2Outputs.get(component)) {
					newPartition.addSignal(specification.getSignalName(compOutput));
				}
		}

		return newPartition;
	}

}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**profile_id** | **String** | Id of a Profile that will be used for encoding. | [optional]
**profile_name** | **String** | A name of a Profile that will be used for encoding. | [optional]


text:
using System;
using System.Threading;
using System.Threading.Tasks;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Web.Scheduling;

namespace Umbraco.Web.PublishedCache.XmlPublishedCache
{
    /// <summary>
    /// This is the background task runner that persists the xml file to the file system
    /// </summary>
    /// <remarks>
    /// This is used so that all file saving is done on a web aware worker background thread and all logic is performed async so this
    /// process will not interfere with any web requests threads. This is also done as to not require any global locks and to ensure that
    /// if multiple threads are performing publishing tasks that the file will be persisted in accordance with the final resulting
    /// xml structure since the file writes are queued.
    /// </remarks>
    internal class XmlStoreFilePersister : LatchedBackgroundTaskBase
    {
        private readonly IBackgroundTaskRunner<XmlStoreFilePersister> _runner;
        private readonly ILogger _logger;
        private readonly XmlStore _store;
        private readonly object _locko = new object();
        private bool _released;
        private Timer _timer;
        private DateTime _initialTouch;
        private readonly AsyncLock _runLock = new AsyncLock(); // ensure we run once at a time

        // note:
        // as long as the runner controls the runs, we know that we run once at a time, but
        // when the AppDomain goes down and the runner has completed and yet the persister is
        // asked to save, then we need to run immediately - but the runner may be running, so
        // we need to make sure there's no collision - hence _runLock

        private const int WaitMilliseconds = 4000; // save the cache 4s after the last change (ie every 4s min)
        private const int MaxWaitMilliseconds = 30000; // save the cache after some time (ie no more than 30s of changes)

        // save the cache when the app goes down
        public override bool RunsOnShutdown => _timer != null;

        // initialize the first instance, which is inactive (not touched yet)
        public XmlStoreFilePersister(IBackgroundTaskRunner<XmlStoreFilePersister> runner, XmlStore store, ILogger logger)
            : this(runner, store, logger, false)
        { }

        // initialize further instances, which are active (touched)
        private XmlStoreFilePersister(IBackgroundTaskRunner<XmlStoreFilePersister> runner, XmlStore store, ILogger logger, bool touched)
        {
            _runner = runner;
            _store = store;
            _logger = logger;

            if (_runner.TryAdd(this) == false)
            {
                _runner = null; // runner's down
                _released = true; // don't mess with timer
                return;
            }

            // runner could decide to run it anytime now

            if (touched == false) return;

            _logger.Debug<XmlStoreFilePersister>("Created, save in {WaitMilliseconds}ms.", WaitMilliseconds);
            _initialTouch = DateTime.Now;
            _timer = new Timer(_ => TimerRelease());
            _timer.Change(WaitMilliseconds, 0);
        }

        public XmlStoreFilePersister Touch()
        {
            // if _released is false then we're going to setup a timer
            //  then the runner wants to shutdown & run immediately
            //  this sets _released to true & the timer will trigger eventualy & who cares?
            // if _released is true, either it's a normal release, or
            //  a runner shutdown, in which case we won't be able to
            //  add a new task, and so we'll run immediately

            var ret = this;
            var runNow = false;

            lock (_locko)
            {
                if (_released) // our timer has triggered OR the runner is shutting down
                {
                    _logger.Debug<XmlStoreFilePersister>("Touched, was released...");

                    // release: has run or is running, too late, return a new task (adds itself to runner)
                    if (_runner == null)
                    {
                        _logger.Debug<XmlStoreFilePersister>("Runner is down, run now.");
                        runNow = true;
                    }
                    else
                    {
                        _logger.Debug<XmlStoreFilePersister>("Create new...");
                        ret = new XmlStoreFilePersister(_runner, _store, _logger, true);
                        if (ret._runner == null)
                        {
                            // could not enlist with the runner, runner is completed, must run now
                            _logger.Debug<XmlStoreFilePersister>("Runner is down, run now.");
                            runNow = true;
                        }
                    }
                }

                else if (_timer == null) // we don't have a timer yet
                {
                    _logger.Debug<XmlStoreFilePersister>("Touched, was idle, start and save in {WaitMilliseconds}ms.", WaitMilliseconds);
                    _initialTouch = DateTime.Now;
                    _timer = new Timer(_ => TimerRelease());
                    _timer.Change(WaitMilliseconds, 0);
                }

                else // we have a timer
                {
                    // change the timer to trigger in WaitMilliseconds unless we've been touched first more
                    // than MaxWaitMilliseconds ago and then leave the time unchanged

                    if (DateTime.Now - _initialTouch < TimeSpan.FromMilliseconds(MaxWaitMilliseconds))
                    {
                        _logger.Debug<XmlStoreFilePersister>("Touched, was waiting, can delay, save in {WaitMilliseconds}ms.", WaitMilliseconds);
                        _timer.Change(WaitMilliseconds, 0);
                    }
                    else
                    {
                        _logger.Debug<XmlStoreFilePersister>("Touched, was waiting, cannot delay.");
                    }
                }
            }

            // note: this comes from 7.x where it was not possible to lock the entire content service
            // in our case, the XmlStore configures everything so that it is not possible to access content
            // when going down, so this should never happen.

            if (runNow)
                //Run();
                _logger.Warn<XmlStoreFilePersister>("Cannot write now because we are going down, changes may be lost.");

            return ret; // this, by default, unless we created a new one
        }

        private void TimerRelease()
        {
            lock (_locko)
            {
                _logger.Debug<XmlStoreFilePersister>("Timer: release.");
                _released = true;

                Release();
            }
        }

        public override bool IsAsync => false;

        public override void Run()
        {
            lock (_locko)
            {
                _logger.Debug<XmlStoreFilePersister>("Run now (sync).");
                // not really needed but safer (it's only us invoking Run, but the method is public...)
                _released = true;
            }

            using (_runLock.Lock())
            {
                _store.SaveXmlToFile();
            }
        }

        protected override void DisposeResources()
        {
            base.DisposeResources();

            // stop the timer
            if (_timer == null) return;
            _timer.Change(Timeout.Infinite, Timeout.Infinite);
            _timer.Dispose();
        }
    }
}


text:
// Created by Ron 'Maxwolf' McDowell (ron.mcdowell@gmail.com)
// Timestamp 01/03/2016@1:50 AM

using System;
using System.Collections.Generic;

namespace OregonTrail
{
    ///
    ///     Acts like a unique identifier for each event that is to be registered in the system and defines several special
    ///     things about that we want in a key such as category, name, and if it should be random or not.
    ///
    public sealed class EventKey : IComparer<EventKey>, IComparable<EventKey>, IEquatable<EventKey>,
        IEqualityComparer<EventKey>
    {
        /// Initializes a new instance of the <see cref="T:OregonTrail.EventKey" /> class.
        /// <param name="category">The category.</param>
        /// <param name="name">The name.</param>
        /// <param name="executionType">The execution Type.</param>
        public EventKey(EventCategory category, string name, EventExecution executionType)
        {
            ExecutionType = executionType;
            Category = category;
            Name = name;
        }

        ///
        ///     Category the event should fall under so when we select by type we can include this event in that selection.
        ///
        public EventCategory Category { get; }

        ///
        ///     Name of the event, typically this is the type name but it really could be anything.
        ///
        public string Name { get; }

        ///
        ///     Determines if this event will be selected for being chosen at random when events are fired by category and not
        ///     directly by their type.
        ///
        public EventExecution ExecutionType { get; }

        /// Compares the current object with another object of the same type.
        /// <returns>
        ///     A value that indicates the relative order of the objects being compared. The return value has the following
        ///     meanings: Value Meaning Less than zero This object is less than the <paramref name="other" /> parameter.Zero This
        ///     object is equal to <paramref name="other" />. Greater than zero This object is greater than
        ///     <paramref name="other" />.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public int CompareTo(EventKey other)
        {
            var result = string.Compare(other.Name, Name, StringComparison.Ordinal);
            if (result != 0) return result;

            return result;
        }

        ///
        ///     Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the
        ///     other.
        ///
        /// <returns>
        ///     A signed integer that indicates the relative values of <paramref name="x" /> and <paramref name="y" />, as shown in
        ///     the following table.Value Meaning Less than zero<paramref name="x" /> is less than <paramref name="y" />.Zero
        ///     <paramref name="x" /> equals <paramref name="y" />.Greater than zero<paramref name="x" /> is greater than
        ///     <paramref name="y" />.
        /// </returns>
        /// <param name="x">The first object to compare.</param>
        /// <param name="y">The second object to compare.</param>
        public int Compare(EventKey x, EventKey y)
        {
            var result = string.Compare(x.Name, y.Name, StringComparison.Ordinal);
            if (result != 0) return result;

            return result;
        }

        /// Determines whether the specified objects are equal.
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <returns>true if the specified objects are equal; otherwise, false.</returns>
        public bool Equals(EventKey x, EventKey y)
        {
            return x.Equals(y);
        }

        /// Returns a hash code for the specified object.
        /// <returns>A hash code for the specified object.</returns>
        /// <param name="obj">The <see cref="T:System.Object" /> for which a hash code is to be returned.</param>
        /// <exception cref="T:System.ArgumentNullException">
        ///     The type of <paramref name="obj" /> is a reference type and
        ///     <paramref name="obj" /> is null.
        /// </exception>
        public int GetHashCode(EventKey obj)
        {
            var hash = 23;
            hash = (hash*31) + Name.GetHashCode();
            return hash;
        }

        /// Indicates whether the current object is equal to another object of the same type.
        /// <returns>true if the current object is equal to the <paramref name="other" /> parameter; otherwise, false.</returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(EventKey other)
        {
            // Reference equality check
            if (this == other)
            {
                return true;
            }

            if (other == null)
            {
                return false;
            }

            if (other.GetType() != GetType())
            {
                return false;
            }

            if (Name.Equals(other.Name))
            {
                return true;
            }

            return false;
        }

        ///
        ///     Returns a string that represents the current object.
        ///
        /// <returns>
        ///     A string that represents the current object.
        /// </returns>
        public override string ToString()
        {
            return Name;
        }
    }
}


text:
using UnityEngine;

public class SearchableResource : MonoBehaviour
{
	[Header("Type")] public string Type = "default";
	[Header("Amount")] public int Amount;
	public string Resource = "wood";

	// Use this for initialization
	void Start () {
		switch (Type)
		{
			case "Wood":
			{
				Amount = Random.Range(1, 10);
				Resource = "wood";
				break;
			}
			case "Stone":
			{
				Amount = Random.Range(1, 10);
				Resource = "stone";
				break;
			}
			default:
			{
				Amount = Random.Range(1, 6);
				Resource = "wood";
				break;
			}
		}
	}

	// Update is called once per frame
	void Update () {

	}
}