text:
package de.tobiaserthal.akgbensheim.backend.preferences;

import android.content.Context;
import android.content.Intent;
import android.content.PeriodicSync;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.ColorInt;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import de.tobiaserthal.akgbensheim.backend.R;
import de.tobiaserthal.akgbensheim.backend.model.ModelUtils;
import de.tobiaserthal.akgbensheim.backend.sync.SyncAdapter;
import de.tobiaserthal.akgbensheim.backend.sync.SyncUtils;
import de.tobiaserthal.akgbensheim.backend.utils.Log;

import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeyColorCancel;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeyColorChange;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeyColorOther;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeyColorReserv;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeyColorRoomSubst;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeyColorShift;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeyColorSpecial;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeyColorSubst;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeyDataOnlyWifi;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeySubstFilter;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeySubstForm;
import static de.tobiaserthal.akgbensheim.backend.preferences.PreferenceKeychain.getKeySubstPhase;

/**
 * A helper class designed to help accessing the relevant preferences for this application
 * without the need to know all the keys and access the storage directly.
 */
public class PreferenceProvider {
    public static final String TAG = "PreferenceProvider";
    public static final String ACTION_SUBST = "de.tobiaserthal.akgbensheim.data.preferences.ACTION_SUBST";

    private static final int BROADCAST_COLOR = 0;
    private static final int BROADCAST_SUBST = 1;

    private static PreferenceProvider instance;

    private Context context;
    private SharedPreferences preferences;

    private String[] phaseOptions;
    private int[] phaseOptionValues;

    private String[] formOptions;
    private String[] formOptionValues;

    private String[] frequencyOptions;
    private int[] frequencyOptionValues;

    private final SharedPreferences.OnSharedPreferenceChangeListener changeListener
            = new SharedPreferences.OnSharedPreferenceChangeListener() {
        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            Log.d(TAG, "Preference change detected for key: %s", key);

            int type = -1;
            String action = null;
            if(getKeyColorSubst(getContext())               .equals(key)
                    || getKeyColorCancel(getContext())      .equals(key)
                    || getKeyColorChange(getContext())      .equals(key)
                    || getKeyColorReserv(getContext())      .equals(key)
                    || getKeyColorRoomSubst(getContext())   .equals(key)
                    || getKeyColorShift(getContext())       .equals(key)
                    || getKeyColorSpecial(getContext())     .equals(key)
                    || getKeyColorOther(getContext())       .equals(key)) {

                action = ACTION_SUBST;
                type = BROADCAST_COLOR;
            } else if(getKeySubstPhase(getContext())        .equals(key)
                    || getKeySubstForm(getContext())        .equals(key)
                    || getKeySubstFilter(getContext())      .equals(key)) {

                action = ACTION_SUBST;
                type = BROADCAST_SUBST;
            }

            if(action != null) {
                Log.d(TAG, "Sending Broadcast event for type: %d", type);

                Intent intent = new Intent(action);
                intent.putExtra("type", type);

                LocalBroadcastManager
                        .getInstance(context)
                        .sendBroadcast(intent);
            }
        }
    };

    private PreferenceProvider(Context context) {
        this.context = context.getApplicationContext();

        this.preferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        this.preferences.registerOnSharedPreferenceChangeListener(changeListener);

        this.phaseOptions = context.getResources().getStringArray(R.array.pref_subst_phase_options);
        this.phaseOptionValues = context.getResources().getIntArray(R.array.pref_subst_phase_options_values);

        this.formOptions = context.getResources().getStringArray(R.array.pref_subst_form_options);
        this.formOptionValues = context.getResources().getStringArray(R.array.pref_subst_form_options_values);

        this.frequencyOptions = context.getResources().getStringArray(R.array.pref_subst_sync_frequency_options);
        this.frequencyOptionValues = context.getResources().getIntArray(R.array.pref_subst_sync_frequency_options_values);

        ensureSubstPhase();
        ensureSubstForm();
        ensureWifiOnly();
    }

    private void ensureWifiOnly() {
        if(!preferences.contains(getKeyDataOnlyWifi(getContext()))) {
            setOnlyWifiEnabled(false);
        }
    }

    private void ensureSubstForm() {
        if(!preferences.contains(getKeySubstForm(getContext()))) {
            setSubstFormIndex(0);
        }
    }

    private void ensureSubstPhase() {
        if(!preferences.contains(getKeySubstPhase(getContext()))) {
            setSubstPhaseIndex(0);
        }
    }

    public static synchronized PreferenceProvider initialize(Context context) {
        instance = new PreferenceProvider(context);
        return instance;
    }

    public static synchronized PreferenceProvider getInstance() {
        if(instance == null) {
            throw new IllegalStateException("PreferenceProvider not initialized!");
        }

        return instance;
    }

    public static void destroyInstance(PreferenceProvider instance) {
        if (instance != null) {
            instance.preferences.unregisterOnSharedPreferenceChangeListener(instance.changeListener);
            instance.preferences = null;

            Arrays.fill(instance.phaseOptions, null);
            Arrays.fill(instance.phaseOptionValues, 0);

            Arrays.fill(instance.formOptions, null);
            Arrays.fill(instance.formOptionValues, null);

            Arrays.fill(instance.frequencyOptions, null);
            Arrays.fill(instance.frequencyOptionValues, 0);
        }
    }

    public Context getContext() {
        return context;
    }

    /**
     * Get the current selected phase for substitution filtering
     * @return The current phase or the first value in the available options as default
     */
    public int getSubstPhase() {
        return preferences.getInt(getKeySubstPhase(getContext()), phaseOptionValues[0]);
    }

    public int getSubstPhaseIndex() {
        int index = Arrays.binarySearch(phaseOptionValues, getSubstPhase());
        return index < 0 ? 0 : index;
    }

    public String getSubstPhaseSummary() {
        return phaseOptions[getSubstPhaseIndex()];
    }

    public String[] getSubsPhaseSummaries() {
        return phaseOptions;
    }

    public void setSubstPhase(int phase) {
        int index = Arrays.binarySearch(phaseOptionValues, phase);
        setSubstPhaseIndex(index);
    }

    public void setSubstPhaseIndex(int index) {
        int phase = phaseOptionValues[Math.min(Math.max(index, 0), phaseOptionValues.length - 1)];
        preferences.edit()
                .putInt(getKeySubstPhase(getContext()), phase)
                .apply();
    }

    public static int getSubstPhaseSek2() {
        return 10;
    }

    /**
     * Get the current selected form for substitution filtering
     * @return The current form or the first value in the available options as default
     */
    public String getSubstForm() {
        return preferences.getString(getKeySubstForm(getContext()), formOptionValues[0]);
    }

    public int getSubstFormIndex() {
        int index = Arrays.binarySearch(formOptionValues, getSubstForm());
        return index < 0 ? 0 : index;
    }

    public String getSubstFormSummary() {
        return formOptions[getSubstFormIndex()];
    }

    public String[] getSubstFormSummaries() {
        return formOptions;
    }

    public void setSubstForm(String form) {
        int index = Arrays.binarySearch(formOptionValues, form);
        setSubstFormIndex(index);
    }

    public void setSubstFormIndex(int index) {
        String form = formOptionValues[Math.min(Math.max(index, 0), formOptionValues.length - 1)];
        preferences.edit()
                .putString(getKeySubstForm(getContext()), form)
                .apply();
    }

    /**
     * Get a list of terms that should be used to filter
     * for specific subjects affected by substitutions.
     * @return The current form or the first value in the available options as default
     */
    public String[] getSubstSubjects() {
        String csv = preferences.getString(getKeySubstFilter(getContext()), null);
        if(TextUtils.isEmpty(csv)) {
            return null;
        }

        return csv.split(",");
    }

    public void setSubstSubjects(String csv) {
        preferences.edit()
                .putString(getKeySubstFilter(getContext()), csv)
                .apply();
    }

    public String getSubstSubjectsSummary() {
        String[] set = getSubstSubjects();
        if(set == null) {
            return null;
        }

        StringBuilder builder = new StringBuilder();
        int iterations = (set.length < 3 ? set.length : 3);
        for (int i = 0; i < iterations; i++) {
            builder.append(set[i]);

            if(i < iterations - 1) {
                builder.append(", ");
            } else if(set.length > 3) {
                builder.append("...");
            }
        }

        return builder.toString();
    }

    /**
     * Find out whether the user wants data to be fetched only when connected via wifi.
     * @return The user setting as a boolean
     */
    public boolean isOnlyWifiEnabled() {
        return preferences.getBoolean(getKeyDataOnlyWifi(getContext()), false);
    }

    public void setOnlyWifiEnabled(boolean onlyWifi) {
        preferences.edit()
                .putBoolean(getKeyDataOnlyWifi(getContext()), onlyWifi)
                .apply();
    }

    /**
     * Find out whether the user wants data to be synced whenever the
     * system broadcasts a network tickle.
     * @return The user setting as a boolean.
     */
    public boolean isAutoSyncEnabled() {
        return SyncUtils.shouldSyncAutomatically();
    }

    public void setAutoSyncEnabled(boolean autoSync) {
        SyncUtils.setSyncAutomatically(autoSync);
    }

    public int getFrequencyIndex(int frequency) {
        int index = Arrays.binarySearch(frequencyOptionValues, frequency);
        return index < 0 ? 0 : index;
    }

    public int getFrequency(int index) {
        return frequencyOptionValues[Math.min(Math.max(index, 0), frequencyOptionValues.length)];
    }

    public String getFrequencySummary(int index) {
        return frequencyOptions[Math.min(Math.max(index, 0), frequencyOptions.length)];
    }

    public String[] getFrequencySummaries() {
        return frequencyOptions;
    }

    public ArrayList<PeriodicSyncPreference> getAllSyncs() {
        /* Create the array and fill it with the predefined dummies.
         * This is necessary since disabled syncs are not saved by the system,
         * so we need create the same static array as always by ourselves :( */
        ArrayList<PeriodicSyncPreference> periodicSyncDummies = new ArrayList<>();
        periodicSyncDummies.add(new PeriodicSyncPreference(ModelUtils.NEWS, context.getString(R.string.model_title_news)));
        periodicSyncDummies.add(new PeriodicSyncPreference(ModelUtils.EVENTS, context.getString(R.string.model_title_events)));
        periodicSyncDummies.add(new PeriodicSyncPreference(ModelUtils.TEACHERS, context.getString(R.string.model_title_teachers)));
        periodicSyncDummies.add(new PeriodicSyncPreference(ModelUtils.SUBSTITUTIONS, context.getString(R.string.model_title_subst)));

        // get the current active periodic syncs from the system
        List<PeriodicSync> periodicSyncs = SyncUtils.getPeriodicSyncs();

        // map them to their model identifier
        HashMap<Integer, PeriodicSync> syncHashMap = new HashMap<>();
        for(int i = 0; i < periodicSyncs.size(); i ++) {
            PeriodicSync sync = periodicSyncs.get(i);

            if(sync != null && sync.extras != null) {
                int which = sync.extras.getInt(SyncAdapter.ARGS.ID, -1);
                Log.d(TAG, "Periodic sync #%d: typeFlag: %d, %s",
                        i, which, sync.toString());

                syncHashMap.put(which, sync);
            }
        }

        /* Now we go through our array and look for additional info
         * about each sync provided by the array from the system */
        for(int i = 0; i < periodicSyncDummies.size(); i ++) {
            PeriodicSyncPreference syncDummy = periodicSyncDummies.get(i);
            PeriodicSync sync = syncHashMap.get(syncDummy.getWhich());

            if(sync != null) {
                syncDummy.setEnabled(true);

                int index = getFrequencyIndex((int) sync.period);
                syncDummy.setFrequency(getFrequency(index));
                syncDummy.setSubtitle(getFrequencySummary(index));
            }
        }

        // Do cleanup
        syncHashMap.clear();
        periodicSyncs.clear();

        return periodicSyncDummies;
    }

    public void dispatchAllSyncs(ArrayList<PeriodicSyncPreference> dummies) {
        if(dummies == null) {
            return;
        }

        // go through each dummy entry
        for(int i = 0; i < dummies.size(); i ++) {
            PeriodicSyncPreference dummy = dummies.get(i);
            if(dummy.isEnabled()) {
                Log.d(TAG, "Adding/updating periodic sync #%d: typeFlag: %d", i, dummy.getWhich());
                SyncUtils.requestPeriodic(dummy.getWhich(), dummy.getFrequency());
            } else {
                Log.d(TAG, "Removing periodic sync #%d: typeFlag: %d", i, dummy.getWhich());
                SyncUtils.removePeriodic(dummy.getWhich());
            }
        }
    }

    public static class PeriodicSyncPreference {
        private int which;
        private String title;
        private int frequency;
        private String subtitle;
        private boolean enabled;

        public PeriodicSyncPreference(int which, String title, int frequency, boolean enabled) {
            this.which = which;
            this.title = title;
            this.frequency = frequency;
            this.subtitle = "";
            this.enabled = enabled;
        }

        public PeriodicSyncPreference(int which, String title) {
            this.which = which;
            this.title = title;
            this.frequency = 0;
            this.subtitle = "";
            this.enabled = false;
        }

        public int getWhich() {
            return which;
        }

        public String getTitle() {
            return title;
        }

        public int getFrequency() {
            return frequency;
        }

        public String getSubtitle() {
            return subtitle;
        }

        public boolean isEnabled() {
            return enabled;
        }

        public void setWhich(int which) {
            this.which = which;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public void setFrequency(int frequency) {
            this.frequency = frequency;
        }

        public void setSubtitle(String subtitle) {
            this.subtitle = subtitle;
        }

        public void setEnabled(boolean enabled) {
            this.enabled = enabled;
        }
    }

    @ColorInt
    public int getColorSubst() {
        return preferences.getInt(
                getKeyColorSubst(getContext()),
                ContextCompat.getColor(context, R.color.subst_indigo));
    }

    @ColorInt
    public int getColorChange() {
        return preferences.getInt(
                getKeyColorChange(getContext()),
                ContextCompat.getColor(context, R.color.subst_indigo));
    }

    @ColorInt
    public int getColorReserv() {
        return preferences.getInt(getKeyColorReserv(getContext()),
                ContextCompat.getColor(context, R.color.subst_indigo));
    }

    @ColorInt
    public int getColorCancel() {
        return preferences.getInt(getKeyColorCancel(getContext()),
                ContextCompat.getColor(context, R.color.subst_indigo));
    }

    @ColorInt
    public int getColorSpecial() {
        return preferences.getInt(getKeyColorSpecial(getContext()),
                ContextCompat.getColor(context, R.color.subst_indigo));
    }

    @ColorInt
    public int getColorRoomSubst() {
        return preferences.getInt(getKeyColorRoomSubst(getContext()),
                ContextCompat.getColor(context, R.color.subst_indigo));
    }

    @ColorInt
    public int getColorShift() {
        return preferences.getInt(getKeyColorShift(getContext()),
                ContextCompat.getColor(context, R.color.subst_indigo));
    }

    @ColorInt
    public int getColorOther() {
        return preferences.getInt(getKeyColorOther(getContext()),
                ContextCompat.getColor(context, R.color.subst_indigo));
    }

    @ColorInt
    public int getColorFromType(String type) {
        if(type.equalsIgnoreCase("Vertretung"))
            return getColorSubst();

        if(type.equalsIgnoreCase("Tausch"))
            return getColorChange();

        if(type.equalsIgnoreCase("Vormerkung"))
            return getColorReserv();

        if(type.equalsIgnoreCase("Fällt aus!"))
            return getColorCancel();

        if(type.equalsIgnoreCase("Sondereins."))
            return getColorSpecial();

        if(type.equalsIgnoreCase("Raum-Vtr."))
            return getColorRoomSubst();

        if(type.equalsIgnoreCase("Verlegung"))
            return getColorShift();

        return getColorOther();
    }

    public void setColorSubst(@ColorInt int color) {
        preferences.edit()
                .putInt(getKeyColorSubst(getContext()), color)
                .apply();
    }

    public void setColorChange(@ColorInt int color) {
        preferences.edit()
                .putInt(getKeyColorChange(getContext()), color)
                .apply();
    }

    public void setColorReserv(@ColorInt int color) {
        preferences.edit()
                .putInt(getKeyColorReserv(getContext()), color)
                .apply();
    }

    public void setColorCancel(@ColorInt int color) {
        preferences.edit()
                .putInt(getKeyColorCancel(getContext()), color)
                .apply();
    }

    public void setColorSpecial(@ColorInt int color) {
        preferences.edit()
                .putInt(getKeyColorSpecial(getContext()), color)
                .apply();
    }

    public void setColorRoomSubst(@ColorInt int color) {
        preferences.edit()
                .putInt(getKeyColorRoomSubst(getContext()), color)
                .apply();
    }

    public void setColorShift(@ColorInt int color) {
        preferences.edit()
                .putInt(getKeyColorShift(getContext()), color)
                .apply();
    }

    public void setColorOther(@ColorInt int color) {
        preferences.edit()
                .putInt(getKeyColorOther(getContext()), color)
                .apply();
    }
}


text:
CKEDITOR.plugins.setLang( 'find', 'is', {
	find: 'Leita',
	findOptions: 'Find Options',
	findWhat: 'Leita að:',
	matchCase: 'Gera greinarmun á¡ há¡- og lágstöfum',
	matchCyclic: 'Match cyclic',
	matchWord: 'Aðeins heil orð',
	notFoundMsg: 'Leitartexti fannst ekki!',
	replace: 'Skipta út',
	replaceAll: 'Skipta út allsstaðar',
	replaceSuccessMsg: '%1 occurrence(s) replaced.',
	replaceWith: 'Skipta út fyrir:',
	title: 'Finna og skipta'
} );

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Serialization;
using Grabacr07.KanColleWrapper;

namespace Grabacr07.KanColleViewer.Models.Migration
{
	/// <summary>互換性のために残されています。</summary>
	[Obsolete]
	[Serializable]
	[XmlRoot("KanColleClientSettings")]
	[EditorBrowsable(EditorBrowsableState.Never)]
	// ReSharper disable once InconsistentNaming
	public class _KanColleClientSettings : IKanColleClientSettings
	{
		public int NotificationShorteningTime { get; set; }
		public int ReSortieCondition { get; set; }
		public string ViewRangeCalcType { get; set; }
		public bool IsViewRangeCalcIncludeFirstFleet { get; set; }
		public bool IsViewRangeCalcIncludeSecondFleet { get; set; }
		public bool CheckFlagshipIsRepairShip { get; set; }

		event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
		{
			add { }
			remove { }
		}
	}
}


text:
package org.osgi.framework.hooks.weaving;

import org.osgi.annotation.versioning.ConsumerType;

/**
 * OSGi Framework Weaving Hook Service.
 *
 *

 * Bundles registering this service will be called during framework class
 * loading operations. Weaving hook services are called when a class is being
 * loaded by the framework and have an opportunity to transform the class file
 * bytes that represents the class being loaded. Weaving hooks may also ask the
 * framework to wire in additional dynamic imports to the bundle.
 *
 *

 * When a class is being loaded, the framework will create a {@link WovenClass}
 * object for the class and pass it to each registered weaving hook service for
 * possible modification. The first weaving hook called will see the original
 * class file bytes. Subsequently called weaving hooks will see the class file
 * bytes as modified by previously called weaving hooks.
 *
 * @ThreadSafe
 * @author $Id$
 */
@ConsumerType
public interface WeavingHook {
	/**
	 * Weaving hook method.
	 *

	 * This method can modify the specified woven class object to weave the
	 * class being defined.
	 *

	 * If this method throws any exception, the framework must log the exception
	 * and fail the class load in progress. This weaving hook service must be
	 * deny listed by the framework and must not be called again. The deny
	 * listing of this weaving hook service must expire when this weaving hook
	 * service is unregistered. However, this method can throw a
	 * {@link WeavingException} to deliberately fail the class load in progress
	 * without being deny listed by the framework.
	 *
	 * @param wovenClass The {@link WovenClass} object that represents the data
	 *            that will be used to define the class.
	 * @throws WeavingException If this weaving hook wants to deliberately fail
	 *             the class load in progress without being deny listed by the
	 *             framework
	 */
	public void weave(WovenClass wovenClass);
}


text:
+ Upgraded dependency on ReactiveCocoa to 4.1.0.
+ Bumped minimum platform to iOS 8.0.

# Release 0.3.1

+ Removed PVGTableViewCellWithCollectionViewModel protocol
+ Added nullability annotations
+ Fixes project settings

# Release 0.3.0

+ Adds protection in PVGTableViewProxy against multiple view models having the same unique id. The implementation removes the extra view models silently.

# Release 0.2.1

+ Reverted rendering method back to a synchronous one to fix unwanted animations on UITableView.
+ Made sure that loadMore is called asyncronously to prevent regression with pagination.

# Relase 0.2.0

+ Replaces NSTimer runloop with dispatch async to fix rendering of multiple sections.


text:
<?php
/*
Plugin Name: giploy
Plugin URI: http://wordpress.org/extend/plugins/giploy/
Description: This plugin allows you to deploy Github hotsted theme or plugin with service hook.
Author: Takahashi Fumiki
Version: 1.0
Author URI: http://takahashifumiki.com
Text Domain: giploy
*/

// Do not load directly
defined('ABSPATH') or die();

// Add text domain
load_plugin_textdomain('giploy', false, 'giploy/language');

if( version_compare(PHP_VERSION, '5.3.0') >= 0 && (version_compare(PHP_VERSION, '5.3.0') >= 0 || ini_get('short_open_tag')) ){
    // O.K. Load bootsrap.
    require __DIR__.'/app/bootstrap.php';
}else{

    /**
     * Show error message on admin
     *
     * @ignore
     */
    function _giploy_error(){
        printf('

%s

', sprintf(__('[giploy Error] Your PHP version is %s, but giploy requires 5.3.0 and over. And on 5.3.*, you must set short_open_tag = on because <?= tags are used here and there. For more info, see PHP Manual', 'giploy'), PHP_VERSION, 'http://www.php.net/manual/en/ini.core.php'));
    }
    // If PHP is < 5.3, show message and finish.
    add_action('admin_notices', '_giploy_error');
}


text:
#include <cybergarage/x3d/BooleanToggleNode.h>

using namespace CyberX3D;

static const char set_booleanFieldString[] = "set_boolean";
static const char toggleFieldString[] = "toggle";

BooleanToggleNode::BooleanToggleNode()
{
	setHeaderFlag(false);
	setType(BOOLEANTOGGLE_NODE);

	// set_booleanEvent eventIn field
	set_booleanField = new SFBool();
	addEventIn(set_booleanFieldString, set_booleanField);

	// toggle eventIn field
	toggleField = new SFBool(false);
	addExposedField(toggleFieldString, toggleField);
}

BooleanToggleNode::~BooleanToggleNode()
{
}

////////////////////////////////////////////////
//	setBoolean
////////////////////////////////////////////////

SFBool *BooleanToggleNode::getBooleanField() const
{
	if (isInstanceNode() == false)
		return set_booleanField;
	return (SFBool*)getEventIn(set_booleanFieldString);
}

void BooleanToggleNode::setBoolean(bool value)
{
	getBooleanField()->setValue(value);
}

bool BooleanToggleNode::getBoolean()  const
{
	return getBooleanField()->getValue();
}

bool BooleanToggleNode::isBoolean()  const
{
	return getBooleanField()->getValue();
}

////////////////////////////////////////////////
//	toggle
////////////////////////////////////////////////

SFBool *BooleanToggleNode::getToggleField() const
{
	if (isInstanceNode() == false)
		return toggleField;
	return (SFBool*)getExposedField(toggleFieldString);
}

void BooleanToggleNode::setToggle(bool value)
{
	getToggleField()->setValue(value);
}

bool BooleanToggleNode::getToggle()  const
{
	return getToggleField()->getValue();
}

bool BooleanToggleNode::isToggle()  const
{
	return getToggleField()->getValue();
}

////////////////////////////////////////////////
//	functions
////////////////////////////////////////////////

bool BooleanToggleNode::isChildNodeType(Node *node) const
{
	return false;
}

void BooleanToggleNode::initialize()
{
}

void BooleanToggleNode::uninitialize()
{
}

void BooleanToggleNode::update()
{
}

////////////////////////////////////////////////
//	Output
////////////////////////////////////////////////

void BooleanToggleNode::outputContext(std::ostream &printStream, const char *indentString)  const
{
}

////////////////////////////////////////////////
//	List
////////////////////////////////////////////////

BooleanToggleNode *BooleanToggleNode::next()  const
{
	return (BooleanToggleNode *)Node::next(getType());
}

BooleanToggleNode *BooleanToggleNode::nextTraversal()  const
{
	return (BooleanToggleNode *)Node::nextTraversalByType(getType());
}


text:
Implementation of a key/column/value store is in `shift.com/key_column_value_store.py`

KeyColumnValueStore is the implementation, using pure python dict and tuples.

RedisKeyColumnValueStore is a incomplete implementation that supports backing the data to redis.

##### REST API server
implemention a rest server that interfaces with KeyColumnValueStore in `shift.com/server.py`
you can run as follows
```
source bashrc
./run_server.sh
```

##### unitest to ensure functionality
`tests` dir includes all unittest
you can run as follows
```
source bashrc
./test_runner.sh
```
Ensure you have the web server running, else the `rest_api_test.py` will fail.

##### Persisted file
`codetestdata` is a preserved state of the store used in `load_from_file_test.py`
`kcv_store.pkl` is the default file that the store loads from is persisted to. `disk_persistance_test.py` deletes it every time it runs.

##### External dependencies
have been included in `requirements.txt`

### Implementation overview

##### Persisted disk file overview
Pickeled file on disk, consists of two objects
1. a dict containing the inital store state. for ex. `{'store': {...}}`
2. a sequence of operations performed on the store after intial load for ex `{'op': {'func': 'set', args': [key, val, col]}}`

Firstly, we load the initial store state from this file.
Secondly, we replay all operations sequentially.
Finally persist the current store state back to disk.

##### op_queue worker
We spin off a worker process to write operation sequentially to disk.
every operation wih side effects puts itself on this queue, before returning the results.
This helps to keep this async and avoid data corruption.

### Limitations and improvements
* RedisKeyColumnValueStore is incomplete, redis might me appropriate to scale.
* if the process where to crash, all inflight ops in op_queue will be lost without getting a chance to be written to disk.
* tornado server handlers could be made coroutines with yields.
* a two level of hash structure would be more efficient on redis, to avoid pickling loads and dumps.
{
    ...
    '<key>': [<column_name> ...(sorted list of column_names)]
    '<key>': [<column_name> ...(sorted list of column_names)]
    '<key>': [<column_name> ...(sorted list of column_names)]
    ...
}

{
    ...
    '<key>-<column_name>': <value>
    '<key>-<column_name>': <value>
    '<key>-<column_name>': <value>
    ...
}


text:
module T10997 where

import T10997a

{- With ghc-7.10.2:

    The interface for 'T10997a'
    Declaration for Just'
    Pattern synonym Just':
    Iface type variable out of scope:  k
    Cannot continue after interface file error
-}

bar :: (Showable a) => Maybe a -> Maybe a
bar (Just' a) = Just' a


text:
                    <input type="text" class="form-control" placeholder="Otsi...">

                                <button class="btn btn-default" type="button">

                                </button>

                 Uudised

                 Õppetulemused

                 Tööde esitamine


text:
require 'conduit/fusion/parsers/base'

module Conduit::Driver::Fusion
  class CancelPort::Parser < Parser::Base
  end
end


text:
using System;
using System.Drawing;

namespace ImageSearchAPILib
{
    /// <summary>
    /// 画像検索APIが実装すべき機能
    /// </summary>
    public interface IImageSearchAPI
    {
        string APIName { get; }
        object[] Params { get; set; }
        object[] DefaultParams { get; }
        ImageData[] ImageDatas { get; }

        event EventHandler SearchError;
        event EventHandler SearchFinished;
        event ImageLoadedEventHandler ImageLoaded;

        void Search(string query);
    }

    public class ImageData
    {
        public Bitmap Bitmap { get; set; }
        public string FileName { get; set; }
        public string SourceURL { get; set; }
    }

    public delegate void ImageLoadedEventHandler(object sender, ImageLoadedEventArgs e);

    public class ImageLoadedEventArgs
        : EventArgs
    {
        public int Index { get; set; }
        public ImageData ImageData { get; set; }
    }
}


text:
package main

import (
	"testing"
	"github.com/<%= userName %>/<%= appNameSlug %>"
)

func TestReturnMsg(t *testing.T) {
	msg := "Testing Message func"
	testMsg := <%= appNameSlug %>.ReturnMsg(msg)
	if msg != testMsg {
		t.Errorf("'%s' is different of '%s'", msg, testMsg)
	}
}


text:
<?php
/**
 * Mail Wrapper
 *
 * PHP Version 5
 *
 * @author   Richard Seymour <web@bespoke.support>
 * @license  MIT
 * @link     https://github.com/BespokeSupport/MailWrapper
 */

namespace BespokeSupport\MailWrapper\Tests;

use BespokeSupport\MailWrapper\MailAddressManager;
use BespokeSupport\MailWrapper\TesterEntity\TesterEmailEntity;
use BespokeSupport\MailWrapper\TesterEntity\TesterEmailEntityString;

/**
 * Class MailParseTest
 * @package BespokeSupport\MailWrapper\Tests
 */
class MailParseTest extends MailWrapperTestBootstrap
{
    /**
     *
     */
    public function testString()
    {
        $email = self::$toAddresses[0];
        $this->assertCount(1, MailAddressManager::combineRecipients($email));
    }

    /**
     *
     */
    public function testBoolTrue()
    {
        $email = true;
        $this->assertCount(0, MailAddressManager::combineRecipients($email));
    }

    /**
     *
     */
    public function testBoolFalse()
    {
        $email = false;
        $this->assertCount(0, MailAddressManager::combineRecipients($email));
    }

    /**
     *
     */
    public function testNull()
    {
        $email = null;
        $this->assertCount(0, MailAddressManager::combineRecipients($email));
    }

    /**
     *
     */
    public function testObject()
    {
        $email = new \stdClass();
        $email->email = 'hello1@example.com';
        $this->assertCount(1, MailAddressManager::combineRecipients($email));
    }

    /**
     *
     */
    public function testObjectNull()
    {
        $email = new \stdClass();
        $email->email = null;
        $this->assertCount(0, MailAddressManager::combineRecipients($email));
    }

    /**
     *
     */
    public function testClass()
    {
        $emailString = self::$toAddresses[0];

        $email = new TesterEmailEntity();
        $email->setEmail($emailString);

        $result = MailAddressManager::combineRecipients($email);
        $this->assertCount(1, $result);
        $this->assertEquals($emailString, $result[0]);
    }

    /**
     *
     */
    public function testClassNull()
    {
        $email = new TesterEmailEntity();
        $email->setEmail(null);
        $this->assertCount(0, MailAddressManager::combineRecipients($email));
    }

    /**
     *
     */
    public function testClassStringZero()
    {
        $email = new TesterEmailEntityString();
        $this->assertCount(0, MailAddressManager::combineRecipients($email));
    }

    /**
     *
     */
    public function testClassString()
    {
        $emailString = self::$toAddresses[0];

        $email = new TesterEmailEntityString();
        $email->myEmail = $emailString;

        $result = MailAddressManager::combineRecipients($email);
        $this->assertCount(1, $result);
        $this->assertEquals($emailString, $result[0]);
    }
}


text:
package org.apache.spark.deploy.worker.ui

import java.io.File
import java.net.URI
import javax.servlet.http.HttpServletRequest

import scala.xml.Node

import org.apache.spark.ui.{WebUIPage, UIUtils}
import org.apache.spark.util.Utils
import org.apache.spark.Logging
import org.apache.spark.util.logging.RollingFileAppender

private[ui] class LogPage(parent: WorkerWebUI) extends WebUIPage("logPage") with Logging {
  private val worker = parent.worker
  private val workDir = new File(parent.workDir.toURI.normalize().getPath)
  private val supportedLogTypes = Set("stderr", "stdout")

  def renderLog(request: HttpServletRequest): String = {
    val defaultBytes = 100 * 1024

    val appId = Option(request.getParameter("appId"))
    val executorId = Option(request.getParameter("executorId"))
    val driverId = Option(request.getParameter("driverId"))
    val logType = request.getParameter("logType")
    val offset = Option(request.getParameter("offset")).map(_.toLong)
    val byteLength = Option(request.getParameter("byteLength")).map(_.toInt).getOrElse(defaultBytes)

    val logDir = (appId, executorId, driverId) match {
      case (Some(a), Some(e), None) =>
        s"${workDir.getPath}/$appId/$executorId/"
      case (None, None, Some(d)) =>
        s"${workDir.getPath}/$driverId/"
      case _ =>
        throw new Exception("Request must specify either application or driver identifiers")
    }

    val (logText, startByte, endByte, logLength) = getLog(logDir, logType, offset, byteLength)
    val pre = s"==== Bytes $startByte-$endByte of $logLength of $logDir$logType ====\n"
    pre + logText
  }

  def render(request: HttpServletRequest): Seq[Node] = {
    val defaultBytes = 100 * 1024
    val appId = Option(request.getParameter("appId"))
    val executorId = Option(request.getParameter("executorId"))
    val driverId = Option(request.getParameter("driverId"))
    val logType = request.getParameter("logType")
    val offset = Option(request.getParameter("offset")).map(_.toLong)
    val byteLength = Option(request.getParameter("byteLength")).map(_.toInt).getOrElse(defaultBytes)

    val (logDir, params, pageName) = (appId, executorId, driverId) match {
      case (Some(a), Some(e), None) =>
        (s"${workDir.getPath}/$a/$e/", s"appId=$a&executorId=$e", s"$a/$e")
      case (None, None, Some(d)) =>
        (s"${workDir.getPath}/$d/", s"driverId=$d", d)
      case _ =>
        throw new Exception("Request must specify either application or driver identifiers")
    }

    val (logText, startByte, endByte, logLength) = getLog(logDir, logType, offset, byteLength)
    val linkToMaster =
Back to Master

    val range = Bytes {startByte.toString} - {endByte.toString} of {logLength}

    val backButton =
      if (startByte > 0) {

          <button type="button" class="btn btn-default">
            Previous {Utils.bytesToString(math.min(byteLength, startByte))}
          </button>

      } else {
        <button type="button" class="btn btn-default" disabled="disabled">
          Previous 0 B
        </button>
      }

    val nextButton =
      if (endByte < logLength) {

          <button type="button" class="btn btn-default">
            Next {Utils.bytesToString(math.min(byteLength, logLength - endByte))}
          </button>

      } else {
        <button type="button" class="btn btn-default" disabled="disabled">
          Next 0 B
        </button>
      }

    val content =

          {linkToMaster}

{backButton}

{range}

{nextButton}

{logText}

    UIUtils.basicSparkPage(content, logType + " log page for " + pageName)
  }

  /** Get the part of the log files given the offset and desired length of bytes */
  private def getLog(
      logDirectory: String,
      logType: String,
      offsetOption: Option[Long],
      byteLength: Int
    ): (String, Long, Long, Long) = {

    if (!supportedLogTypes.contains(logType)) {
      return ("Error: Log type must be one of " + supportedLogTypes.mkString(", "), 0, 0, 0)
    }

    // Verify that the normalized path of the log directory is in the working directory
    val normalizedUri = new File(logDirectory).toURI.normalize()
    val normalizedLogDir = new File(normalizedUri.getPath)
    if (!Utils.isInDirectory(workDir, normalizedLogDir)) {
      return ("Error: invalid log directory " + logDirectory, 0, 0, 0)
    }

    try {
      val files = RollingFileAppender.getSortedRolledOverFiles(logDirectory, logType)
      logDebug(s"Sorted log files of type $logType in $logDirectory:\n${files.mkString("\n")}")

      val totalLength = files.map { _.length }.sum
      val offset = offsetOption.getOrElse(totalLength - byteLength)
      val startIndex = {
        if (offset < 0) {
          0L
        } else if (offset > totalLength) {
          totalLength
        } else {
          offset
        }
      }
      val endIndex = math.min(startIndex + byteLength, totalLength)
      logDebug(s"Getting log from $startIndex to $endIndex")
      val logText = Utils.offsetBytes(files, startIndex, endIndex)
      logDebug(s"Got log of length ${logText.length} bytes")
      (logText, startIndex, endIndex, totalLength)
    } catch {
      case e: Exception =>
        logError(s"Error getting $logType logs from directory $logDirectory", e)
        ("Error getting logs due to exception: " + e.getMessage, 0, 0, 0)
    }
  }
}


text:
namespace eCollabro.BAL.Entities.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Data.Entity.Spatial;

    [Table("BlogCategory")]
    public partial class BlogCategory
    {
        public BlogCategory()
        {
            Blogs = new HashSet<Blog>();
        }

        public int BlogCategoryId { get; set; }

        [Required]
        [StringLength(100)]
        public string BlogCategoryName { get; set; }

        [StringLength(255)]
        public string BlogCategoryDescription { get; set; }

        public int SiteId { get; set; }

        public bool IsDeleted { get; set; }

        public bool IsActive { get; set; }

        public bool IsAnomynousAccess { get; set; }

        public int CreatedById { get; set; }

        public DateTime CreatedOn { get; set; }

        public int? ModifiedById { get; set; }

        public DateTime? ModifiedOn { get; set; }

        public virtual ICollection<Blog> Blogs { get; set; }

        public virtual Site Site { get; set; }
    }
}


text:
<?php

namespace Ingewikkeld\LinkTuesdayBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class LinkController extends Controller
{
    /**
     * @extra:Route("/", name="lt_homepage")
     * @extra:Template()
     */
    public function indexAction()
    {
        $em = $this->get('doctrine.orm.default_entity_manager');

        return array(
            'recent'    => $em->getRepository('IngewikkeldLinkTuesdayBundle:Link')->getMostRecentLinks(),
            'top'       => $em->getRepository('IngewikkeldLinkTuesdayBundle:Link')->getMostPopularLinks(),
            'weektop'   => $em->getRepository('IngewikkeldLinkTuesdayBundle:Link')->getMostPopularLinksSince(date('d-m-Y', time()-(86400*7))),
        );
    }

    /**
     * @extra:Route("/feed", name="lt_feed")
     * @extra:Template()
     */
    public function rssAction()
    {
      $em = $this->get('doctrine.orm.default_entity_manager');

      $items = $em->getRepository('IngewikkeldLinkTuesdayBundle:Link')->getMostRecentLinks();

      $templateItems = array();
      foreach($items as $item)
      {
        $templateItems[] = $item[0];
      }

      return array('items' => $templateItems, 'date' => date('c'));
    }
}


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

<WebView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/early_access_web_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:filterTouchesWhenObscured="true"
    android:paddingTop="90dp">

</WebView>


text:
package com.seven.designbox.designpatterns.common.html;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.Window;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.List;

/**
 * @author Cosme Zamudio - Android SDK Examples
 *         I Grabbed this class from the SDK Examples, i actually made a lot of changes, so it
 *         doesnt look like the original one.
 *         it has the prettify functionality inside the class, it may look ugly.. but it works fine
 *         and its well organized (thats what i think)
 *         Note: Im Leaving the original comments, they might come in handy for other users reading
 *         the code
 *
 *         Wraps a WebView widget within an Activity. When launched, it uses the
 *         URI from the intent as the URL to load into the WebView.
 *         It supports all URLs schemes that a standard WebView supports, as well as
 *         loading the top level markup using the file scheme.
 *         The WebView default settings are used with the exception of normal layout
 *         is set.
 *         This activity shows a loading progress bar in the window title and sets
 *         the window title to the title of the content.
 */
public class HTMLViewerPlusPlus extends Activity {

    /**
     * The WebView that is placed in this Activity
     */
    private WebView mWebView;

    /**
     * As the file content is loaded completely into RAM first, set
     * a limitation on the file size so we don't use too much RAM. If someone
     * wants to load content that is larger than this, then a content
     * provider should be used.
     */
    static final int MAXFILESIZE = 16172;
    static final String LOGTAG = "HTMLViewerPlusPlus";
    private static final int PICK_REQUEST_CODE = 0;
    private boolean isSearcihng = false;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.main_menu, menu);
        return true;

    }

    /**
     * Modify the menus according to the searching mode and matches
     */
//    @Override
//    public boolean onPrepareOptionsMenu(Menu menu) {
//        if (isSearcihng) {
//            menu.findItem(R.id.next_menu).setEnabled(true);
//            menu.findItem(R.id.clear_menu).setEnabled(true);
//        } else {
//            menu.findItem(R.id.next_menu).setEnabled(false);
//            menu.findItem(R.id.clear_menu).setEnabled(false);
//        }
//
//
//        return super.onPrepareOptionsMenu(menu);
//    }

//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.open_menu:
//                openFileIntent();
//                break;
//            case R.id.search_menu:
//                showSearchDialog();
//                break;
//            case R.id.next_menu:
//                nextSearch();
//                break;
//            case R.id.clear_menu:
//                clearSearch();
//                break;
//            case R.id.select_menu:
//                selectAndCopyText();
//                break;
//            case R.id.home_menu:
//                loadHomeScreen();
//                break;
//            case R.id.help_menu:
//                loadHelpScreen();
//                break;
//            case R.id.quit_menu:
//                quitApplication();
//                break;
//        }
//        return false;
//
//    }

    /**
     * Added to avoid refreshing the page on orientation change
     * saw it on stackoverflow, dont remember wich article
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**
     * Gets the result from the file picker activity
     * thats the only intent im actually calling (and expecting results from) right now
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == PICK_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Uri uri = intent.getData();
                if (uri != null) {
                    String path = uri.toString();
                    if (path.toLowerCase().startsWith("file://")) {
                        path = (new File(URI.create(path))).getAbsolutePath();
                        loadFile(Uri.parse(path), "text/html");
                    }
                }
            } else {
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CookieSyncManager.createInstance(this);
        requestWindowFeature(Window.FEATURE_PROGRESS);
        mWebView = new WebView(this);
        setContentView(mWebView);

        // Setup callback support for title and progress bar
        //mWebView.setWebChromeClient( new WebChrome() );
        mWebView.setWebViewClient(new WebChrome2());

        // Configure the webview
        WebSettings s = mWebView.getSettings();
        s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        s.setUseWideViewPort(false);
        s.setAllowFileAccess(true);
        s.setBuiltInZoomControls(true);
        s.setLightTouchEnabled(true);
        s.setLoadsImagesAutomatically(true);
        s.setPluginState(WebSettings.PluginState.OFF);
        s.setSupportZoom(true);
        s.setSupportMultipleWindows(true);
        s.setJavaScriptEnabled(true);

        // Restore a webview if we are meant to restore
        if (savedInstanceState != null) {
            mWebView.restoreState(savedInstanceState);
        } else {
            Intent intent = getIntent();
            if (intent.getData() != null) {
                Uri uri = intent.getData();
                if ("file".equals(uri.getScheme())) { //are we opening a file, or some data?
                    loadFile(uri, intent.getType());
                } else {
                    mWebView.loadUrl(intent.getData().toString());
                }
            } else {
                //Home Screen, Simple explanation
                mWebView.loadUrl("file:///android_asset/SimpleFactory.html");
            }
        }
    }

    /**
     * Get a Document Handler Depending on the filename extension
     *
     * @param filename The filename to retrieve the handler from
     * @return The new document handler
     */
    public DocumentHandler getHandlerByExtension(String filename) {
        DocumentHandler handler = null;

        if (filename.endsWith(".java")) handler = new JavaDocumentHandler();
        if (filename.endsWith(".cpp") || filename.endsWith(".cc"))
            handler = new CppDocumentHandler();
        if (filename.endsWith(".c")) handler = new CDocumentHandler();
        if (filename.endsWith(".html") || filename.endsWith(".htm") || filename.endsWith(".xhtml"))
            handler = new HtmlDocumentHandler();
        if (filename.endsWith(".js")) handler = new JavascriptDocumentHandler();
        if (filename.endsWith(".mxml")) handler = new MxmlDocumentHandler();
        if (filename.endsWith(".pl")) handler = new PerlDocumentHandler();
        if (filename.endsWith(".py")) handler = new PythonDocumentHandler();
        if (filename.endsWith(".rb")) handler = new RubyDocumentHandler();
        if (filename.endsWith(".xml")) handler = new XmlDocumentHandler();
        if (filename.endsWith(".css")) handler = new CssDocumentHandler();
        if (filename.endsWith(".el") || filename.endsWith(".lisp") || filename.endsWith(".scm"))
            handler = new LispDocumentHandler();
        if (filename.endsWith(".lua")) handler = new LuaDocumentHandler();
        if (filename.endsWith(".ml")) handler = new MlDocumentHandler();
        if (filename.endsWith(".vb") || filename.endsWith(".bas"))
            handler = new VbDocumentHandler();
        if (filename.endsWith(".sql")) handler = new SqlDocumentHandler();

        if (handler == null) handler = new TextDocumentHandler();
        Log.v(LOGTAG, " Handler: " + filename);
        return handler;
    }

    /**
     * Call the intent to open files
     */
    public void openFileIntent() {
        Intent fileIntent = new Intent(HTMLViewerPlusPlus.this, FileBrowser.class);
        startActivityForResult(fileIntent, PICK_REQUEST_CODE);

    	/* Next Version Feature, support more explorer intents besides the built in one
        Intent intent = new Intent();
		Uri startDir = Uri.fromFile(Environment.getExternalStorageDirectory());

		if (isIntentAvailable(this,"vnd.android.cursor.dir/lysesoft.andexplorer.file")) { //AndExplorer
			intent.setAction(Intent.ACTION_PICK);
			intent.setDataAndType(startDir, "vnd.android.cursor.dir/lysesoft.andexplorer.file");
			intent.putExtra("explorer_title", "Select a file");
			intent.putExtra("browser_title_background_color", "440000AA");
			intent.putExtra("browser_title_foreground_color", "FFFFFFFF");
			intent.putExtra("browser_list_background_color", "00000066");
			intent.putExtra("browser_list_fontscale", "120%");
			intent.putExtra("browser_list_layout", "2");
			startActivityForResult(intent, PICK_REQUEST_CODE);
		}
		else if (isIntentAvailable(this,"org.openintents.action.PICK_FILE")) { //OIFileManager
			intent.setType("org.openintents.action.PICK_FILE");
			intent.setData(startDir);
			startActivityForResult(intent, PICK_REQUEST_CODE);
		} else  {
			Toast.makeText(getApplicationContext(), "No File Manager Detected", 2000).show();
		}
		*/

    }

    /**
     * Function found in the android sdk examples, checks if an action has an intent associated
     * going to be used to check for other filebrowser intents
     *
     * @param context usually this, the context we are working on
     * @param action  the action we want to check the intents
     * @return true if there is at least one intent for that action
     */
    private boolean isIntentAvailable(Context context, String action) {
        final PackageManager packageManager = context.getPackageManager();
        final Intent intent = new Intent(action);
        List<ResolveInfo> list =
                packageManager.queryIntentServices(intent, 0);

        return list.size() > 0;
    }

    /***
     * Closes the application
     */
    public void quitApplication() {
        finish();
    }

    /**
     * Loads the home screen
     */
    public void loadHomeScreen() {
        mWebView.getSettings().setUseWideViewPort(false);
        mWebView.loadUrl("file:///android_asset/SimpleFactory.html");
    }

    /**
     * Loads the help screen
     */
    public void loadHelpScreen() {
        mWebView.getSettings().setUseWideViewPort(false);
        mWebView.loadUrl("file:///android_asset/SimpleFactory.html"); //Need to change for the help screen
    }

    /**
     * Select Text in the webview and automatically sends the selected text to the clipboard
     */
    public void selectAndCopyText() {
        try {
            KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0);
            shiftPressEvent.dispatch(mWebView);
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }

    /**
     * Clear all the matches in the search
     */
    public void clearSearch() {
        isSearcihng = false;
        mWebView.clearMatches();
    }

    /**
     * Find Next Match in Search
     */
    public void nextSearch() {
        mWebView.findNext(true);
    }

    /**
     * Search inside the webview
     */
    public void showSearchDialog() {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("Find Text");
        alert.setMessage("Enter text to find:");

        // Set an EditText view to get user input
        final EditText inputText = new EditText(this);
        alert.setView(inputText);

        alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                String value = inputText.getText().toString();
                isSearcihng = true;
                mWebView.findAll(value);
            }
        });

        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {

            }
        });

        alert.show();
    }

    /**
     * Load the HTML file into the webview by converting it to a data:
     * URL. If there were any relative URLs, then they will fail as the
     * webview does not allow access to the file:/// scheme for accessing
     * the local file system,
     *
     * Note: Before actually loading the info in webview, i add the prettify libraries to do the
     * syntax highlight
     * also i organize the data where it has to be. works fine now but it needs some work
     *
     * @param uri      file URI pointing to the content to be loaded
     * @param mimeType mimetype provided
     */
    private void loadFile(Uri uri, String mimeType) {
        String path = uri.getPath();
        DocumentHandler handler = getHandlerByExtension(path);

        File f = new File(path);
        final long length = f.length();
        if (!f.exists()) {
            Log.e(LOGTAG, "File doesnt exists: " + path);
            return;
        }

        if (handler == null) {
            Log.e(LOGTAG, "Filetype not supported");
            Toast.makeText(HTMLViewerPlusPlus.this, "Filetype not supported", Toast.LENGTH_LONG);
            return;
        }

        // typecast to int is safe as long as MAXFILESIZE < MAXINT
        byte[] array = new byte[(int) length];

        try {
            InputStream is = new FileInputStream(f);
            is.read(array);
            is.close();
        } catch (FileNotFoundException ex) {
            // Checked for file existance already, so this should not happen
            Log.e(LOGTAG, "Failed to access file: " + path, ex);
            return;
        } catch (IOException ex) {
            // read or close failed
            Log.e(LOGTAG, "Failed to access file: " + path, ex);
            return;
        }
        String contentString = "";
        setTitle("Android CodePad - " + path);
        contentString += "<title>" + path + "</title>";
        contentString += "<link href='file:///android_asset/prettify.css' rel='stylesheet' type='text/css'/> ";
        contentString += " ";
        contentString += handler.getFileScriptFiles();
        contentString += "";
        String sourceString = new String(array);

        //contentString += sourceString.replace("\n", "
");
        contentString += handler.getFileFormattedString(sourceString);
        contentString += "  ";
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.loadDataWithBaseURL("file:///android_asset/", contentString, handler.getFileMimeType(), "", "");
        Log.v(LOGTAG, "File Loaded: " + path);
    }

    @Override
    protected void onResume() {
        super.onResume();
        CookieSyncManager.getInstance().startSync();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {

        mWebView.saveState(outState);
    }

    @Override
    protected void onStop() {
        super.onStop();

        CookieSyncManager.getInstance().stopSync();
        mWebView.stopLoading();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mWebView.destroy();
    }

}


text:
package application

import (
	"fmt"
	"github.com/starkandwayne/cf-cli/cf"
	"github.com/starkandwayne/cf-cli/cf/api"
	"github.com/starkandwayne/cf-cli/cf/command_metadata"
	"github.com/starkandwayne/cf-cli/cf/configuration"
	"github.com/starkandwayne/cf-cli/cf/errors"
	"github.com/starkandwayne/cf-cli/cf/models"
	"github.com/starkandwayne/cf-cli/cf/requirements"
	"github.com/starkandwayne/cf-cli/cf/terminal"
	"github.com/cloudfoundry/loggregatorlib/logmessage"
	"github.com/codegangsta/cli"
	"os"
	"regexp"
	"strconv"
	"strings"
	"time"
)

const (
	DefaultStagingTimeout = 15 * time.Minute
	DefaultStartupTimeout = 5 * time.Minute
	DefaultPingerThrottle = 5 * time.Second
)

const LogMessageTypeStaging = "STG"

type Start struct {
	ui               terminal.UI
	config           configuration.Reader
	appDisplayer     ApplicationDisplayer
	appReq           requirements.ApplicationRequirement
	appRepo          api.ApplicationRepository
	appInstancesRepo api.AppInstancesRepository
	logRepo          api.LogsRepository

	StartupTimeout time.Duration
	StagingTimeout time.Duration
	PingerThrottle time.Duration
}

type ApplicationStarter interface {
	SetStartTimeoutInSeconds(timeout int)
	ApplicationStart(app models.Application) (updatedApp models.Application, err error)
}

func NewStart(ui terminal.UI, config configuration.Reader, appDisplayer ApplicationDisplayer, appRepo api.ApplicationRepository, appInstancesRepo api.AppInstancesRepository, logRepo api.LogsRepository) (cmd *Start) {
	cmd = new(Start)
	cmd.ui = ui
	cmd.config = config
	cmd.appDisplayer = appDisplayer
	cmd.appRepo = appRepo
	cmd.appInstancesRepo = appInstancesRepo
	cmd.logRepo = logRepo

	cmd.PingerThrottle = DefaultPingerThrottle

	if os.Getenv("CF_STAGING_TIMEOUT") != "" {
		duration, err := strconv.ParseInt(os.Getenv("CF_STAGING_TIMEOUT"), 10, 64)
		if err != nil {
			cmd.ui.Failed("invalid value for env var CF_STAGING_TIMEOUT\n%s", err)
		}
		cmd.StagingTimeout = time.Duration(duration) * time.Minute
	} else {
		cmd.StagingTimeout = DefaultStagingTimeout
	}

	if os.Getenv("CF_STARTUP_TIMEOUT") != "" {
		duration, err := strconv.ParseInt(os.Getenv("CF_STARTUP_TIMEOUT"), 10, 64)
		if err != nil {
			cmd.ui.Failed("invalid value for env var CF_STARTUP_TIMEOUT\n%s", err)
		}
		cmd.StartupTimeout = time.Duration(duration) * time.Minute
	} else {
		cmd.StartupTimeout = DefaultStartupTimeout
	}

	return
}

func (command *Start) Metadata() command_metadata.CommandMetadata {
	return command_metadata.CommandMetadata{
		Name:        "start",
		ShortName:   "st",
		Description: "Start an app",
		Usage:       "CF_NAME start APP",
	}
}

func (cmd *Start) GetRequirements(requirementsFactory requirements.Factory, c *cli.Context) (reqs []requirements.Requirement, err error) {
	if len(c.Args()) == 0 {
		err = errors.New("Incorrect Usage")
		cmd.ui.FailWithUsage(c)
		return
	}

	cmd.appReq = requirementsFactory.NewApplicationRequirement(c.Args()[0])

	reqs = []requirements.Requirement{requirementsFactory.NewLoginRequirement(), cmd.appReq}
	return
}

func (cmd *Start) Run(c *cli.Context) {
	cmd.ApplicationStart(cmd.appReq.GetApplication())
}

func (cmd *Start) ApplicationStart(app models.Application) (updatedApp models.Application, err error) {
	if app.State == "started" {
		cmd.ui.Say(terminal.WarningColor("App " + app.Name + " is already started"))
		return
	}

	stopLoggingChan := make(chan bool, 1)
	loggingStartedChan := make(chan bool)

	go cmd.tailStagingLogs(app, loggingStartedChan, stopLoggingChan)

	<-loggingStartedChan // block until we have established connection to Loggregator

	cmd.ui.Say("Starting app %s in org %s / space %s as %s...",
		terminal.EntityNameColor(app.Name),
		terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
		terminal.EntityNameColor(cmd.config.SpaceFields().Name),
		terminal.EntityNameColor(cmd.config.Username()),
	)

	state := "STARTED"
	updatedApp, apiErr := cmd.appRepo.Update(app.Guid, models.AppParams{State: &state})
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()

	cmd.waitForInstancesToStage(updatedApp)
	stopLoggingChan <- true

	cmd.ui.Say("")

	cmd.waitForOneRunningInstance(updatedApp)
	cmd.ui.Say(terminal.HeaderColor("\nApp started\n"))

	cmd.appDisplayer.ShowApp(updatedApp)
	return
}

func (cmd *Start) SetStartTimeoutInSeconds(timeout int) {
	cmd.StartupTimeout = time.Duration(timeout) * time.Second
}

func simpleLogMessageOutput(logMsg *logmessage.LogMessage) (msgText string) {
	msgText = string(logMsg.GetMessage())
	reg, err := regexp.Compile("[\n\r]+$")
	if err != nil {
		return
	}
	msgText = reg.ReplaceAllString(msgText, "")
	return
}

func (cmd Start) tailStagingLogs(app models.Application, startChan chan bool, stopChan chan bool) {
	onConnect := func() {
		startChan <- true
	}

	err := cmd.logRepo.TailLogsFor(app.Guid, onConnect, func(msg *logmessage.LogMessage) {
		select {
		case <-stopChan:
			cmd.logRepo.Close()
		default:
			if msg.GetSourceName() == LogMessageTypeStaging {
				cmd.ui.Say(simpleLogMessageOutput(msg))
			}
		}
	})

	if err != nil {
		cmd.ui.Warn("Warning: error tailing logs")
		cmd.ui.Say("%s", err)
		startChan <- true
	}
}

func (cmd Start) waitForInstancesToStage(app models.Application) {
	stagingStartTime := time.Now()
	_, err := cmd.appInstancesRepo.GetInstances(app.Guid)

	for err != nil && time.Since(stagingStartTime) < cmd.StagingTimeout {
		if httpError, ok := err.(errors.HttpError); ok && httpError.ErrorCode() != errors.APP_NOT_STAGED {
			cmd.ui.Say("")
			cmd.ui.Failed(fmt.Sprintf("%s\n\nTIP: use '%s' for more information",
				httpError.Error(),
				terminal.CommandColor(fmt.Sprintf("%s logs %s --recent", cf.Name(), app.Name))))
			return
		}
		cmd.ui.Wait(cmd.PingerThrottle)
		_, err = cmd.appInstancesRepo.GetInstances(app.Guid)
	}
	return
}

func (cmd Start) waitForOneRunningInstance(app models.Application) {
	var runningCount, startingCount, flappingCount, downCount int
	startupStartTime := time.Now()

	for runningCount == 0 {
		if time.Since(startupStartTime) > cmd.StartupTimeout {
			cmd.ui.Failed(fmt.Sprintf("Start app timeout\n\nTIP: use '%s' for more information", terminal.CommandColor(fmt.Sprintf("%s logs %s --recent", cf.Name(), app.Name))))
			return
		}

		instances, apiErr := cmd.appInstancesRepo.GetInstances(app.Guid)
		if apiErr != nil {
			cmd.ui.Wait(cmd.PingerThrottle)
			continue
		}

		totalCount := len(instances)
		runningCount, startingCount, flappingCount, downCount = 0, 0, 0, 0

		for _, inst := range instances {
			switch inst.State {
			case models.InstanceRunning:
				runningCount++
			case models.InstanceStarting:
				startingCount++
			case models.InstanceFlapping:
				flappingCount++
			case models.InstanceDown:
				downCount++
			}
		}

		cmd.ui.Say(instancesDetails(startingCount, downCount, runningCount, flappingCount, totalCount))

		if flappingCount > 0 {
			cmd.ui.Failed(fmt.Sprintf("Start unsuccessful\n\nTIP: use '%s' for more information", terminal.CommandColor(fmt.Sprintf("%s logs %s --recent", cf.Name(), app.Name))))
			return
		}
	}
}

func instancesDetails(startingCount, downCount, runningCount, flappingCount, totalCount int) string {
	details := []string{fmt.Sprintf("%d of %d instances running", runningCount, totalCount)}

	if startingCount > 0 {
		details = append(details, fmt.Sprintf("%d starting", startingCount))
	}

	if downCount > 0 {
		details = append(details, fmt.Sprintf("%d down", downCount))
	}

	if flappingCount > 0 {
		details = append(details, fmt.Sprintf("%d failing", flappingCount))
	}

	return strings.Join(details, ", ")
}


text:
namespace Portal.CMS.Entities.Migrations
{
    using System.Data.Entity.Migrations;

    public partial class AddPageSectionBackupEntity : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.PageSectionBackups",
                c => new
                {
                    PageSectionBackupId = c.Int(nullable: false, identity: true),
                    PageSectionId = c.Int(nullable: false),
                    PageSectionBody = c.String(),
                    DateAdded = c.DateTime(nullable: false),
                })
                .PrimaryKey(t => t.PageSectionBackupId)
                .ForeignKey("dbo.PageSections", t => t.PageSectionId, cascadeDelete: true)
                .Index(t => t.PageSectionId);
        }

        public override void Down()
        {
            DropForeignKey("dbo.PageSectionBackups", "PageSectionId", "dbo.PageSections");
            DropIndex("dbo.PageSectionBackups", new[] { "PageSectionId" });
            DropTable("dbo.PageSectionBackups");
        }
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.0-b52-fcs
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.20 at 12:48:21 PM GMT
//

package weka.core.pmml.jaxbbindings;

import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for Taxonomy element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="Taxonomy">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *           <element ref="{http://www.dmg.org/PMML-4_1}Extension" maxOccurs="unbounded" minOccurs="0"/>
 *           <element ref="{http://www.dmg.org/PMML-4_1}ChildParent" maxOccurs="unbounded"/>
 *         </sequence>
 *         <attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "extension",
    "childParent"
})
@XmlRootElement(name = "Taxonomy")
public class Taxonomy {

    @XmlElement(name = "Extension", namespace = "http://www.dmg.org/PMML-4_1", required = true)
    protected List<Extension> extension;
    @XmlElement(name = "ChildParent", namespace = "http://www.dmg.org/PMML-4_1", required = true)
    protected List<ChildParent> childParent;
    @XmlAttribute(required = true)
    protected String name;

    /**
     * Gets the value of the extension property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the extension property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getExtension().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link Extension }
     *
     *
     */
    public List<Extension> getExtension() {
        if (extension == null) {
            extension = new ArrayList<Extension>();
        }
        return this.extension;
    }

    /**
     * Gets the value of the childParent property.
     *
     *

     * This accessor method returns a reference to the live list,
     * not a snapshot. Therefore any modification you make to the
     * returned list will be present inside the JAXB object.
     * This is why there is not a set method for the childParent property.
     *
     *

     * For example, to add a new item, do as follows:
     *

     *    getChildParent().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list
     * {@link ChildParent }
     *
     *
     */
    public List<ChildParent> getChildParent() {
        if (childParent == null) {
            childParent = new ArrayList<ChildParent>();
        }
        return this.childParent;
    }

    /**
     * Gets the value of the name property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the value of the name property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setName(String value) {
        this.name = value;
    }

}


text:
/**
 * Shopware Store - Global Stores and Models
 *
 * todo@all: Documentation
 */
Ext.define('Shopware.apps.Base.store.PaymentStatus', {
    extend: 'Ext.data.Store',

    alternateClassName: 'Shopware.store.PaymentStatus',
    storeId: 'base.PaymentStatus',
    model : 'Shopware.apps.Base.model.PaymentStatus',
    pageSize: 1000,
    autoLoad: false,
    proxy:{
        type:'ajax',
        url:'{url action="getPaymentStatus"}',
        reader:{
            type: 'json',
            root: 'data',
            totalProperty: 'total'
        }
    }
}).create();


text:
using ICanPay;
using System.Collections.Generic;
using System.Web.Mvc;

namespace MvcDemo.Controllers
{
    public class NotifyController : Controller
    {

        private static List<Merchant> _merchantList;

        static NotifyController()
        {
            InitMerchantList();
        }

        private static void InitMerchantList()
        {
            Merchant alipayMerchant = new Merchant
            {
                GatewayType = GatewayType.Alipay,
                UserName = "000000000000000",                       // 合作伙伴身份(PID)
                Key = "000000000000000000000000000000000000000000"  // MD5密钥
            };

            Merchant weChatPaymentMerchant = new Merchant
            {
                GatewayType = GatewayType.WeChatPay,
                UserName = "000000000000000",                        // 微信支付商户号
                Key = "000000000000000000000000000000000000000000"   // API密钥
            };

            Merchant tenpayMerchant = new Merchant
            {
                GatewayType = GatewayType.Tenpay,
                UserName = "000000000000000",                       // 商户号
                Key = "000000000000000000000000000000000000000000"  // 密钥
            };

            Merchant yeepayMerchant = new Merchant
            {
                GatewayType = GatewayType.Yeepay,
                UserName = "000000000000000",                       // 商户编号
                Key = "000000000000000000000000000000000000000000"  // 商户密钥
            };

            _merchantList = new List<Merchant>
            {
                alipayMerchant,
                weChatPaymentMerchant,
                tenpayMerchant,
                yeepayMerchant
            };
        }

        public ActionResult Index()
        {
            // 订阅支付通知事件
            PaymentNotify notify = new PaymentNotify(_merchantList);
            notify.PaymentSucceed += notify_PaymentSucceed;
            notify.PaymentFailed += notify_PaymentFailed;
            notify.UnknownGateway += notify_UnknownGateway;

            // 接收并处理支付通知
            notify.Received();

            return View();
        }

        private void notify_PaymentSucceed(object sender, PaymentSucceedEventArgs e)
        {
            // 支付成功时的处理代码
            if (e.PaymentNotifyMethod == PaymentNotifyMethod.AutoReturn)
            {
                // 当前是用户的浏览器自动返回时显示支付成功页面
            }
        }

        private void notify_PaymentFailed(object sender, PaymentFailedEventArgs e)
        {
            // 支付失败时的处理代码
        }

        private void notify_UnknownGateway(object sender, UnknownGatewayEventArgs e)
        {
            // 无法识别支付网关时的处理代码
        }
    }
}


text:
require "pure-admin-rails/version"

module PureAdmin
  module Rails
    class Engine < ::Rails::Engine
    end
  end
end


text:
#include <vector>
#include <map>

/*
 * NaCl Functions for intereacting with debuggers
 */

#include "native_client/src/include/nacl_string.h"
#include "native_client/src/shared/platform/nacl_check.h"
#include "native_client/src/shared/platform/nacl_exit.h"
#include "native_client/src/shared/platform/nacl_log.h"
#include "native_client/src/shared/platform/nacl_threads.h"
#include "native_client/src/trusted/debug_stub/debug_stub.h"
#include "native_client/src/trusted/debug_stub/platform.h"
#include "native_client/src/trusted/debug_stub/session.h"
#include "native_client/src/trusted/debug_stub/target.h"
#include "native_client/src/trusted/debug_stub/thread.h"
#include "native_client/src/trusted/service_runtime/nacl_app_thread.h"
#include "native_client/src/trusted/service_runtime/nacl_debug_init.h"
#include "native_client/src/trusted/service_runtime/sel_ldr.h"
#include "native_client/src/trusted/service_runtime/thread_suspension.h"

using port::IPlatform;
using port::IThread;
using port::ITransport;
using port::SocketBinding;

using gdb_rsp::Session;
using gdb_rsp::Target;

#if NACL_WINDOWS
/* Disable warning for unwind disabled when exceptions used */
#pragma warning(disable:4530)
#endif

/*
 * These macro wraps all debugging stub calls to prevent C++ code called
 * by the debugging stub to throw and exception past the C API.  We use
 * this technique to allow the use of STL templates.   We catch bad_alloc
 * separately purely to provide information for debugging purposes.
 */
#define DBG_CATCH_ALL                                                       \
  catch(std::bad_alloc) {                                                  \
    NaClLog(LOG_FATAL, "nacl_debug(%d) : Failed to allocate.\n", __LINE__); \
    NaClExit(-1);                                                          \
  }                                                                         \
  catch(std::exception e) {                                                \
    NaClLog(LOG_FATAL, "nacl_debug(%d) : Caught exception: %s.\n",          \
            __LINE__ , e.what());                                           \
    NaClExit(-1);                                                          \
  }                                                                         \
  catch(...) {                                                             \
    NaClLog(LOG_FATAL, "nacl_debug(%d) : Unexpected exception.\n", __LINE__);\
    NaClExit(-1);                                                           \
  }

static Target *g_target = NULL;
static SocketBinding *g_socket_binding = NULL;

int NaClDebugBindSocket() {
  if (g_socket_binding == NULL) {
    NaClDebugStubInit();
    const char *addr = "127.0.0.1:4014";
    g_socket_binding = SocketBinding::Bind(addr);
    if (g_socket_binding == NULL) {
      NaClLog(LOG_ERROR, "NaClStubThread: Failed to bind TCP port '%s'\n",
              addr);
      return 0;
    }
  }
  return 1;
}

void NaClDebugSetBoundSocket(NaClSocketHandle bound_socket) {
  CHECK(g_socket_binding == NULL);
  g_socket_binding = new SocketBinding(bound_socket);
}

void WINAPI NaClStubThread(void *thread_arg) {
  UNREFERENCED_PARAMETER(thread_arg);

  if (!NaClDebugBindSocket()) {
    return;
  }
  while (1) {
    // Wait for a connection.
    nacl::scoped_ptr<ITransport> trans(g_socket_binding->AcceptConnection());
    if (NULL == trans.get()) continue;

    // Create a new session for this connection
    Session ses(trans.get());
    ses.SetFlags(Session::DEBUG_MASK);

    // Run this session for as long as it lasts
    g_target->Run(&ses);
  }
}

static void ThreadCreateHook(struct NaClAppThread *natp) throw() {
  g_target->TrackThread(natp);
}

static void ThreadExitHook(struct NaClAppThread *natp) throw() {
  g_target->IgnoreThread(natp);
}

static void ProcessExitHook() throw() {
  g_target->Exit();
  NaClDebugStubFini();
}

static const struct NaClDebugCallbacks debug_callbacks = {
  ThreadCreateHook,
  ThreadExitHook,
  ProcessExitHook,
};

/*
 * This function is implemented for the service runtime.  The service runtime
 * declares the function so it does not need to be declared in our header.
 */
int NaClDebugInit(struct NaClApp *nap) {
  if (!NaClFaultedThreadQueueEnable(nap)) {
    NaClLog(LOG_ERROR, "NaClDebugInit: Failed to initialize fault handling\n");
    return 0;
  }
  nap->debug_stub_callbacks = &debug_callbacks;

  CHECK(g_target == NULL);
  g_target = new Target(nap);
  CHECK(g_target != NULL);
  g_target->Init();

  NaClThread *thread = new NaClThread;
  CHECK(thread != NULL);

  NaClLog(LOG_WARNING, "nacl_debug(%d) : Debugging started.\n", __LINE__);
  CHECK(NaClThreadCtor(thread, NaClStubThread, NULL, NACL_KERN_STACK_SIZE));

  return 1;
}


text:
"""
CSEM-Book: Ziolkowski & Slob, 2019, CUP
=======================================

See the notebooks in the repo `empymod/csem-ziolkowski-and-slob
<https://github.com/emsig/csem-ziolkowski-and-slob>`_ for:

    Ziolkowski, A., and E. Slob, 2019, **Introduction to Controlled-Source
    Electromagnetic Methods**: Cambridge University Press; ISBN `9781107058620
    <https://www.cambridge.org/9781107058620>`_.

The notebooks contain all numerical examples of the book, 61 in total,
frequency- and time-domain.

"""
pass  # THIS IS NOT AN ACTUAL EXAMPLE, see text above for the actual repo
# sphinx_gallery_thumbnail_path = '_static/thumbs/ziolkowski2019_CPU.jpg'