text:
Ext.define('Ozone.components.admin.StacksTabPanel',{
    extend: 'Ext.panel.Panel',
    alias: ['widget.stackstabpanel','widget.Ozone.components.admin.StacksTabPanel'],

    //The editor widget the tab is open in
    editPanel: null,

    initComponent: function () {
        var self = this;
        Ext.apply(this, {
            layout: 'fit',
            preventHeader:true,
            border:true,
            initDisabled: true,
            widgetLauncher: null,
            widgetEventingController: null,
            widgetStateHandler: null,
            items:[{
                xtype:'stacksgrid',
                itemId:'stacksgrid',
                preventHeader:true,
                border:false
            }],
            dockedItems:[{
                xtype:'toolbar',
                itemId: 'tbStacksGridHdr',
                cls: 'tbStacksGridHdr',
                dock:'top',
                items:[{
                    xtype:'tbtext',
                    itemId: 'lblStacksGrid',
                    cls: 'tbStacksGridHdr',
                    text:'Stacks'
                },'->',{
                    xtype: 'searchbox',
                    listeners: {
                        searchChanged: {
                            fn: function(cmp, value) {
                                var grid = this.getComponent('stacksgrid');
                                if (grid != null) {
                                    grid.applyFilter(value, ['name', 'description']);
                                }
                            },
                            scope: this
                        }
                    }
                }]
            },{
                xtype:'toolbar',
                dock:'bottom',
                ui:'footer',
                defaults: {
                    minWidth: 80
                },
                items:[{
                    xtype:'button',
                    text:'Add',
                    itemId: 'addButton',
                    handler: function() {
                      this.onAddClicked();
                    },
                    scope: this
                },{
                    xtype:'button',
                    text:'Remove',
                    itemId: 'removeButton',
                    handler: function() {
                        var grid = this.down('#stacksgrid');
                        //TODO make sure this is filtered by the passed in id
                        if(grid) {
                            var records = grid.getSelectionModel().getSelection();
                            if(records && records.length>0) {
                                var store = grid.store;
                                store.remove(records);
                                store.on({
                                    save: {
                                        fn: function(s,b,data) {
                                            store.reload();
                                        }
                                    }
                                });
                                store.save();
                            }
                            else {
                                self.editPanel.showAlert("Error", "You must select at least one stack to remove.")
                            }
                        }
                    },
                    scope:this
                }]
            }]
        });

        this.widgetStateHandler = Ozone.state.WidgetStateHandler.getInstance();

        this.on({
            activate: {
                scope: this,
                fn: function (cmp, opts) {
                    //load store with proper filter
                    var owner = cmp.ownerCt;
                    var grid = cmp.down('#stacksgrid');

                    grid.setStore(Ext.create('Ozone.data.StackStore',cmp.storeCfg));
                    var refreshPagingToolbar = function(operation) {
                        cmp.refreshWidgetLaunchMenu();
                        if (operation.action == "destroy" || operation.action == "create") {
                            var ptb = grid.getBottomToolbar();
                            ptb.doRefresh();
                        }
                    };
                    grid.store.proxy.callback = refreshPagingToolbar;

                    grid.store.on('write', function(store, action, result, records, rs) {
                        //Refresh whatever manager lauched this editor widget
                        OWF.Eventing.publish(this.ownerCt.channel, {
                            action: action,
                            domain: this.ownerCt.domain,
                            records: result
                        });
                    }, this);

                    if (grid && owner) {
                        owner.record = owner.recordId ? owner.store.getAt(owner.store.findExact('id', owner.recordId)) : undefined;
                    }

                    // Set the title
                    if (owner.record) {
                        var titleText = Ext.htmlEncode(Ext.util.Format.ellipsis(owner.record.get('title'), 25)) || 'Stacks';
                        var title = cmp.getDockedItems('toolbar[dock="top"]')[0].getComponent('lblStacksGrid');
                        title.setText(titleText);
                    }

                    OWF.Preferences.getUserPreference({
                        namespace: 'owf.admin.StackEditCopy',
                        name: 'guid_to_launch',
                        onSuccess: function(result) {
                            cmp.guid_EditCopyWidget = result.value;
                        },
                        onFailure: function(err) { /* No op */
                            self.editPanel.showAlert('Preferences Error', 'Error looking up Stack Editor: ' + err);
                        }
                    });

                    if(grid && owner) {
                        var compId = owner.recordId ? owner.recordId: -1;
                        var p = {
                            tab:'stacks'
                        };
                        p[cmp.componentId] = compId;
                        grid.setBaseParams(p);
                        grid.on({
                            itemdblclick: {
                                fn: function() {
                                    var records = grid.getSelectionModel().getSelection();
                                    if (records && records.length > 0) {
                                        for (var i = 0; i < records.length; i++) {
                                            cmp.doEdit(records[i].data.id, records[i].data.name);
                                        }
                                    }
                                    else {
                                        self.editPanel.showAlert("Error", "You must select at least one stack to edit.");
                                    }
                                },
                                scope: this
                            }
                        });
                    }
                },
                single: true
            }
        });

        //reload store everytime the tab is activated
        this.on({
           activate: {
             fn: function() {
               var grid = this.getComponent('stacksgrid');
               var store = grid.getStore();
               if (store) {
                   store.load({
                       params: {
                           offset: 0,
                           max: store.pageSize
                       }
                   });
               }
             },
             scope: this
           }
        });

        this.callParent();
    },
    onAddClicked: function (button, e) {
        var record = this.ownerCt.record,
            itemName = record.get('name') ? record.get('name') : record.get('userRealName');

        var win = Ext.widget('admineditoraddwindow', {
            addType: 'Stack',
            itemName: itemName,
            editor: this.editor,
            focusOnClose: this.down(),
            existingItemsStore: this.getComponent('stacksgrid').getStore(),
            searchFields: ['displayName'],
            grid: Ext.widget('stacksgrid', {
                itemId: 'stacksaddgrid',
                border: false,
                preventHeader:true,
                enableColumnHide: false,
                sortableColumns: false
            })
        });
        win.show();
    },
    doEdit: function(id, title) {
        var self = this;
        var dataString = Ozone.util.toString({
            id: id,
            copyFlag: false
        });

        OWF.Launcher.launch({
            title: '$1 - ' + title,
            titleRegex: /(.*)/,
            guid: this.guid_EditCopyWidget,
            launchOnlyIfClosed: false,
            data: dataString
        }, function(response) {
            if (response && response.error) {
                self.editPanel.showAlert('Launch Error', 'Stack Editor Launch Failed: ' + response.message);
            }
        });
    },
    refreshWidgetLaunchMenu: function() {
        if (this.widgetStateHandler) {
            this.widgetStateHandler.handleWidgetRequest({
                fn: 'refreshWidgetLaunchMenu'
            });
        }
    }
});


text: export const NAME = 'BreadcrumbActions';

redpajama_set_name: RedPajamaGithub


text:
using namespace Kore;

namespace {
    Display display;
}

int Display::count() {
	return 1;
}

Display* Display::primary() {
	return &display;
}

Display* Display::get(int index) {
    if (index > 0) {
        return nullptr;
    }
	return &display;
}

DisplayMode Display::availableMode(int index) {
	DisplayMode mode;
	mode.width = 800;
	mode.height = 600;
	mode.frequency = 60;
	mode.bitsPerPixel = 32;
	return mode;
}

int Display::countAvailableModes() {
	return 1;
}

int Display::pixelsPerInch() {
    JNIEnv* env;
    KoreAndroid::getActivity()->vm->AttachCurrentThread(&env, nullptr);
    jclass koreActivityClass = KoreAndroid::findClass(env, "tech.kode.kore.KoreActivity");
    jmethodID koreActivityGetScreenDpi = env->GetStaticMethodID(koreActivityClass, "getScreenDpi", "()I");
    int dpi = env->CallStaticIntMethod(koreActivityClass, koreActivityGetScreenDpi);
    KoreAndroid::getActivity()->vm->DetachCurrentThread();
    return dpi;
}

DisplayData::DisplayData() {}

bool Display::available() {
	return true;
}

const char* Display::name() {
	return "Display";
}

int Display::x() {
	return 0;
}

int Display::y() {
	return 0;
}

int Display::width() {
	JNIEnv* env;
	KoreAndroid::getActivity()->vm->AttachCurrentThread(&env, nullptr);
	jclass koreActivityClass = KoreAndroid::findClass(env, "tech.kode.kore.KoreActivity");
	jmethodID koreActivityGetScreenDpi = env->GetStaticMethodID(koreActivityClass, "getDisplayWidth", "()I");
	int width = env->CallStaticIntMethod(koreActivityClass, koreActivityGetScreenDpi);
	KoreAndroid::getActivity()->vm->DetachCurrentThread();
	return width;
}

int Display::height() {
	JNIEnv* env;
	KoreAndroid::getActivity()->vm->AttachCurrentThread(&env, nullptr);
	jclass koreActivityClass = KoreAndroid::findClass(env, "tech.kode.kore.KoreActivity");
	jmethodID koreActivityGetScreenDpi = env->GetStaticMethodID(koreActivityClass, "getDisplayHeight", "()I");
	int height = env->CallStaticIntMethod(koreActivityClass, koreActivityGetScreenDpi);
	KoreAndroid::getActivity()->vm->DetachCurrentThread();
	return height;
}

int Display::frequency() {
	return 60;
}

Display::Display() {

}


text:
typedef void(^ADAuthorizationCodeCallback)(NSString*, ADAuthenticationError*);

extern NSString* kAdalResumeDictionaryKey;
extern NSString* s_brokerAppVersion;
extern NSString* s_brokerProtocolVersion;

@interface ADAuthenticationRequest (Broker)

+ (BOOL)internalHandleBrokerResponse:(NSURL*)response;

+ (BOOL)validBrokerRedirectUri:(NSString*)url;

- (BOOL)canUseBroker;

- (NSURL *)composeBrokerRequest:(ADAuthenticationError* __autoreleasing *)error;

@end


text: WordCamp Belgrade 2016 styles


text:
Originally created for the [Rock Raiders United](http://rockraidersunited.org) [Racers Tournament](http://www.rockraidersunited.org/topic/4763-rru-racers-tournament-1/)
to randomly select a track for racing, **LEGO Racers Track Selector** randomly selects a track
from the 1999 High Voltage Software PC game *LEGO® Racers* for you to race on.

## Download ##
Download **LEGO Racers Track Selector** from the [Releases](https://github.com/le717/LR-Track-Selector/releases) page.

## License ##
[The MIT License](LICENSE)


text:
define(['jquery'], function($) {

    // Login page logic
    return function() {
        var warnUsername = false;
        var warnPassword = false;

        // Register handler
        $('#btn_register').click(function() {
            // Hide login page and display lobby
            $('#login').addClass('hidden');
            $('#registration').removeClass('hidden');
        });

        // Login handler
        $('#btn_login').click(function() {
            var username = $('#txt_username').val();
            var password = $('#txt_password').val();
            // Make sure the username and password fields are not empty
            if (username.length === 0) {
                $('#warn_username').html('<-- Username cannot be empty');
                warnUsername = true;
            }
            if (password.length === 0) {
                $('#warn_password').html('<-- Password cannot be empty');
                warnPassword = true;
            }
            if (warnUsername || warnPassword) {
                return;
            }
            // Send login request to server
            $.ajax({
                type: "POST",
                url: '/login',
                data: {
                    player: username,
                    password: password
                },
                success: function(data) {
                    if (!data.success) {
                        // Login attempt was not successful
                        // Clear password and prompt to retry
                        $('#txt_password').val('');
                        $('#warn_login').html('Invalid username or password. Try again.');
                    } else {
                        // Hide login page and display lobby
                        $('#login').addClass('hidden');
                        $('#content').removeClass('hidden').trigger('start', [username]);
                    }
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    $('#warn_login').html('AJAX call failed: ' + textStatus + ' ' + errorThrown);
                },
                dataType: "json"
            });
        });

        // Username text field changed handler
        $('#txt_username').keyup(function() {
            if (warnUsername && $(this).val().length > 0) {
                $('#warn_username').html('');
                warnUsername = false;
            }
        });

        // Password text field changed handler
        $('#txt_password').keyup(function() {
            if (warnPassword && $(this).val().length > 0) {
                $('#warn_password').html('');
                warnPassword = false;
            }
        });
    };
});


text:
name: Other
about: General discussion and any other issues.
title: ''
labels: ''
assignees: ''

---


text:
package ark.data.feature;

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

import ark.data.Context;
import ark.data.annotation.Datum;
import ark.data.annotation.Datum.Tools.LabelIndicator;
import ark.parse.ARKParsableFunction;
import ark.parse.Assignment;
import ark.parse.AssignmentList;
import ark.parse.Obj;

/**
 * Feature represents an abstract feature to be computed on data and
 * used in a model.
 *
 * Implementations of particular features derive from the Feature class,
 * and the Feature class is primarily responsible for providing the
 * methods necessary for deserializing features from
 * configuration files.  The features are defined by strings in the
 * configuration file of the form:
 *
 * feature(_[featureReferenceName](_ignored))=[featureGenericName]([parameterName1]=[parameterValue1],...)
 *
 * Where strings in parentheses are optional and strings in square brackets
 * are replaced by feature specific information.
 *
 * A feature's computed values are generally vectors of real values.
 * Each component of a feature's vector has a name, and the set of all names
 * for components is the feature's 'vocabulary'.
 *
 * @author Bill McDowell
 *
 * @param <D> datum type
 * @param <L> datum label type
 */
public abstract class Feature<D extends Datum<L>, L> extends ARKParsableFunction {
	protected Context<D, L> context;

	/**
	 * @param dataSet
	 * @return true if the feature has been initialized for the dataSet
	 */
	public abstract boolean init(FeaturizedDataSet<D, L> dataSet);

	/**
	 * @param datum
	 * @return a sparse mapping from vector indices to values of the feature
	 * for the given datum.
	 */
	public abstract Map<Integer, Double> computeVector(D datum, int offset, Map<Integer, Double> vector);

	/**
	 * @return the length of the vector computed by this feature for each
	 * datum
	 */
	public abstract int getVocabularySize();

	/**
	 *
	 * @param index
	 * @return the name of the component at the given index within vectors
	 * computed by this feature
	 *
	 */
	public abstract String getVocabularyTerm(int index);

	/**
	 *
	 * @param index
	 * @param term
	 * @return true if the name of component at the given index has been set
	 * to the value of term.  This is used when deserializing features that
	 * were previously computed and saved.
	 *
	 */
	protected abstract boolean setVocabularyTerm(int index, String term);

	protected abstract <T extends Datum<Boolean>> Feature<T, Boolean> makeBinaryHelper(Context<T, Boolean> context, LabelIndicator<L> labelIndicator, Feature<T, Boolean> binaryFeature);

	protected abstract boolean cloneHelper(Feature<D, L> clone);

	protected abstract boolean fromParseInternalHelper(AssignmentList internalAssignments);

	protected abstract AssignmentList toParseInternalHelper(AssignmentList internalAssignments);

	/**
	 * @return a generic instance of the feature.  This is used when deserializing
	 * the parameters for the feature from a configuration file
	 */
	public abstract Feature<D, L> makeInstance(Context<D, L> context);

	public Map<Integer, Double> computeVector(D datum) {
		return computeVector(datum, 0, new HashMap<Integer, Double>());
	}

	/**
	 * @return true if this feature should be ignored by models (it is only used for the
	 * computation of other features)
	 */
	public boolean isIgnored() {
		return this.getModifiers().contains("ignored");
	}

	public Map<Integer, String> getSpecificShortNamesForIndices(Iterable<Integer> indices, int offset, Map<Integer, String> specificShortNames) {
		String prefix = getReferenceName() + "_";

		for (Integer index : indices) {
			specificShortNames.put(index + offset, prefix + getVocabularyTerm(index));
		}

		return specificShortNames;
	}

	public Map<Integer, String> getVocabularyForIndices(Iterable<Integer> indices) {
		Map<Integer, String> vocabulary = new HashMap<Integer, String>();
		for (Integer index : indices) {
			vocabulary.put(index, getVocabularyTerm(index));
		}

		return vocabulary;
	}

	public List<String> getSpecificShortNames(List<String> specificShortNames) {
		String prefix = getReferenceName() + "_";
		int vocabularySize = getVocabularySize();
		for (int i = 0; i < vocabularySize; i++) {
			String vocabularyTerm = getVocabularyTerm(i);
			specificShortNames.add(prefix + ((vocabularyTerm == null) ? "" : vocabularyTerm));
		}

		return specificShortNames;
	}

	public Feature<D, L> clone(boolean cloneInternal) {
		Feature<D, L> clone = this.context.getDatumTools().makeFeatureInstance(getGenericName(), this.context);

		if (cloneInternal) {
			if (!clone.fromParse(getModifiers(), getReferenceName(), toParse()))
				return null;
		} else {
			clone.referenceName = this.referenceName;
			clone.modifiers = this.modifiers;

			String[] parameterNames = getParameterNames();
			for (int i = 0; i < parameterNames.length; i++)
				clone.setParameterValue(parameterNames[i], getParameterValue(parameterNames[i]));

			if (!cloneHelper(clone))
				return null;
		}

		return clone;
	}

	public <T extends Datum<Boolean>> Feature<T, Boolean> makeBinary(Context<T, Boolean> context, LabelIndicator<L> labelIndicator) {
		Feature<T, Boolean> binaryFeature = context.getDatumTools().makeFeatureInstance(getGenericName(), context);

		binaryFeature.referenceName = this.referenceName;
		binaryFeature.modifiers = this.modifiers;

		String[] parameterNames = getParameterNames();
		for (int i = 0; i < parameterNames.length; i++)
			binaryFeature.setParameterValue(parameterNames[i], getParameterValue(parameterNames[i]));

		return makeBinaryHelper(context, labelIndicator, binaryFeature);
	}

	@Override
	protected boolean fromParseInternal(AssignmentList internalAssignments) {
		if (internalAssignments == null)
			return true;

		if (internalAssignments.contains("vocabulary")) {
			Obj.Array vocabulary = (Obj.Array)internalAssignments.get("vocabulary").getValue();
			for (int i = 0; i < vocabulary.size(); i++) {
				if (!setVocabularyTerm(i, vocabulary.getStr(i)))
					return false;
			}
		}

		return fromParseInternalHelper(internalAssignments);
	}

	@Override
	protected AssignmentList toParseInternal() {
		AssignmentList internalAssignments = new AssignmentList();

		Obj.Array vocabulary = new Obj.Array();
		for (int i = 0; i < getVocabularySize(); i++) {
			vocabulary.add(Obj.stringValue(getVocabularyTerm(i)));
		}

		if (vocabulary.size() > 0) {
			internalAssignments.add(
					Assignment.assignmentTyped(new ArrayList<String>(), Context.ARRAY_STR, "vocabulary", vocabulary)
			);
		}

		internalAssignments = toParseInternalHelper(internalAssignments);

		return (internalAssignments.size() == 0) ? null : internalAssignments;
	}
}


text:
***You know, there is flood of Arduino compatible boards out there. Why care about yet another?***

yada yada yada... - that's why!

## MCU's speak by timing changes of charge

I love getting a new development board! You might remember getting your first Arduino board and hooking it up to your computer. Then writing:

```cpp

	int ledPin = 13;
	void setup()
	{
		pinMode(ledPin, OUTPUT);
	}
	void loop()
	{
		digitalWrite(ledPin, HIGH);
		delay(1000);
		digitalWrite(ledPin, LOW);
		delay(1000);
	}
```

Yeah, a slow blinking LED! Arduino were the first to make getting started on programming embedded devices, extremely simple and easy.

But as the initial enthusiasm wears off, you begin wondering how you build an automatic tweet button, a [Philips Hue](http://meethue.com) light control switch or some integration with your [Nest](https://nest.com) thermostat? I realized I needed a way of communicating with my Arduino, because I do not speak SPI nor UART - my computer do - but I do not .

### A build-in Display

To enable easy communication with humans, we need to attach a display shield to our Arduino. Have you tried doing that? First check the voltage levels fits, then there is the SPI or parallel interface to the diaplay controller chip, finally we use Adafrait's displays library to draw some simple shaped on the screen. That was my weekend - half fun, half frustrating!

*Mono comes with a touch display built-in, and includes display drivers along with a sophisticated UI Widget and touch event system.*

### Build-in Wireless

OK, are we now ready to do some real things with a Arduino and display shield? It depends, because what I really would like to controlling my Hue lights using [Philips Hue API](http://www.developers.meethue.com), which is JSON based Web API. So I buy a Wifi shield to attach to my Arduino.

Now, I already have a display shield attached - but luckily it fits together after only rewiring the SPI and CS signals, along with some re-fitting of the voltage supply lines.


text:
@implementation SFLoginAndRegister

+ (nullable SFloginRegisterViewController*)createLoginAndRegisterViewControllerWithType:(startType)type completed:(void (^)(NSDictionary * _Nullable))completed {
    SFLoginAndRegister *loginAndRe=[[self alloc]init];
    if (type==startType_Launch) {
        loginAndRe.loginRegisterViewController=[[SFloginRegisterViewController alloc]initWithNibName:@"SFloginRegisterViewController" bundle:[NSBundle bundleForClass:[self class]]withBlock:completed];
    } else if (type==startType_InApp) {
        loginAndRe.loginRegisterViewController=[[SFloginRegisterViewController alloc]initWithNibName:@"SFloginRegisterViewController" bundle:[NSBundle bundleForClass:[self class]]withBlock:completed];
    }
    return loginAndRe.loginRegisterViewController;

}

- (void)dismissLoginAndRegisterViewController:(BOOL)animated completion:(void (^ _Nullable)(void))completion {
    [_loginRegisterViewController dismissViewControllerAnimated:animated completion:completion];
}

@end


text:
using SuperMap.WinRT.Utilities;
using System;
using SuperMap.WinRT.Core;
using Windows.Data.Json;
namespace SuperMap.WinRT.REST
{
    /// ${REST_CoordSys_Title}
    public class CoordSys
    {
        /// ${REST_CoordSys_constructor_D}
        public CoordSys()
        { }
        /// ${REST_CoordSys_attribute_Unit_D}
        public Unit Unit { get; set; }
        /// ${REST_CoordSys_attribute_SpatialRefType_D}
        public SpatialRefType SpatialRefType { get; set; }
        /// ${REST_CoordSys_attribute_PrimeMeridian_D}
        public PrimeMeridian PrimeMeridian { get; set; }
        /// ${REST_CoordSys_attribute_Name_D}
        public string Name { get; set; }
        /// ${REST_CoordSys_attribute_Type_D}
        public CoordSysType Type { get; set; }
        /// ${REST_CoordSys_attribute_Datum_D}
        public Datum Datum { get; set; }

        internal static CoordSys FromJson(JsonObject json)
        {
            if (json == null)
            {
                return null;
            }

            return new CoordSys
            {
                Unit = (Unit)Enum.Parse(typeof(Unit), json["unit"].GetStringEx(), true),
                SpatialRefType = (SpatialRefType)Enum.Parse(typeof(SpatialRefType), json["spatialRefType"].GetStringEx(), true),
                PrimeMeridian = PrimeMeridian.FromJson(json["primeMeridian"].GetObjectEx()),
                Name = json["name"].GetStringEx(),
                Type = (CoordSysType)Enum.Parse(typeof(CoordSysType), json["type"].GetStringEx(), true),
                Datum = Datum.FromJson(json["datum"].GetObjectEx()),
            };
        }
    }
}


text:
package msgpack

import (
	"reflect"

	"github.com/vmihailenco/msgpack/v4/codes"
)

var sliceStringType = reflect.TypeOf(([]string)(nil))

func encodeStringValue(e *Encoder, v reflect.Value) error {
	return e.EncodeString(v.String())
}

func encodeByteSliceValue(e *Encoder, v reflect.Value) error {
	return e.EncodeBytes(v.Bytes())
}

func encodeByteArrayValue(e *Encoder, v reflect.Value) error {
	if err := e.EncodeBytesLen(v.Len()); err != nil {
		return err
	}

	if v.CanAddr() {
		b := v.Slice(0, v.Len()).Bytes()
		return e.write(b)
	}

	e.buf = grow(e.buf, v.Len())
	reflect.Copy(reflect.ValueOf(e.buf), v)
	return e.write(e.buf)
}

func grow(b []byte, n int) []byte {
	if cap(b) >= n {
		return b[:n]
	}
	b = b[:cap(b)]
	b = append(b, make([]byte, n-len(b))...)
	return b
}

func (e *Encoder) EncodeBytesLen(l int) error {
	if l < 256 {
		return e.write1(codes.Bin8, uint8(l))
	}
	if l < 65536 {
		return e.write2(codes.Bin16, uint16(l))
	}
	return e.write4(codes.Bin32, uint32(l))
}

func (e *Encoder) encodeStrLen(l int) error {
	if l < 32 {
		return e.writeCode(codes.FixedStrLow | codes.Code(l))
	}
	if l < 256 {
		return e.write1(codes.Str8, uint8(l))
	}
	if l < 65536 {
		return e.write2(codes.Str16, uint16(l))
	}
	return e.write4(codes.Str32, uint32(l))
}

func (e *Encoder) EncodeString(v string) error {
	if err := e.encodeStrLen(len(v)); err != nil {
		return err
	}
	return e.writeString(v)
}

func (e *Encoder) EncodeBytes(v []byte) error {
	if v == nil {
		return e.EncodeNil()
	}
	if err := e.EncodeBytesLen(len(v)); err != nil {
		return err
	}
	return e.write(v)
}

func (e *Encoder) EncodeArrayLen(l int) error {
	if l < 16 {
		return e.writeCode(codes.FixedArrayLow | codes.Code(l))
	}
	if l < 65536 {
		return e.write2(codes.Array16, uint16(l))
	}
	return e.write4(codes.Array32, uint32(l))
}

func encodeStringSliceValue(e *Encoder, v reflect.Value) error {
	ss := v.Convert(sliceStringType).Interface().([]string)
	return e.encodeStringSlice(ss)
}

func (e *Encoder) encodeStringSlice(s []string) error {
	if s == nil {
		return e.EncodeNil()
	}
	if err := e.EncodeArrayLen(len(s)); err != nil {
		return err
	}
	for _, v := range s {
		if err := e.EncodeString(v); err != nil {
			return err
		}
	}
	return nil
}

func encodeSliceValue(e *Encoder, v reflect.Value) error {
	if v.IsNil() {
		return e.EncodeNil()
	}
	return encodeArrayValue(e, v)
}

func encodeArrayValue(e *Encoder, v reflect.Value) error {
	l := v.Len()
	if err := e.EncodeArrayLen(l); err != nil {
		return err
	}
	for i := 0; i < l; i++ {
		if err := e.EncodeValue(v.Index(i)); err != nil {
			return err
		}
	}
	return nil
}


text:
package org.wso2.wsf.ide.creation.core.command;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.wst.command.internal.env.core.common.StatusUtils;
import org.eclipse.wst.common.frameworks.datamodel.AbstractDataModelOperation;
import org.eclipse.wst.ws.internal.wsrt.IWebService;
import org.eclipse.wst.ws.internal.wsrt.WebServiceScenario;
import org.wso2.wsf.ide.consumption.core.utils.DefaultCodegenUtil;
import org.wso2.wsf.ide.core.context.ServiceContext;
import org.wso2.wsf.ide.core.context.WSASEmitterContext;
import org.wso2.wsf.ide.core.plugin.WebServiceWSASCorePlugin;
import org.wso2.wsf.ide.core.plugin.messages.WSASCoreUIMessages;
import org.wso2.wsf.ide.core.utils.WSASCoreUtils;
import org.wso2.wsf.ide.core.utils.FacetContainerUtils;
import org.wso2.wsf.ide.creation.core.data.DataModel;
import org.wso2.wsf.ide.creation.core.utils.CommonUtils;

public class WSASDefaultingCommand extends AbstractDataModelOperation
{
	private DataModel model;
	private IWebService ws;
	private int scenario;
	IStatus status;

	public WSASDefaultingCommand( DataModel model ,IWebService ws, int scenario)
	{
		this.model = model;
		this.ws=ws;
		this.scenario=scenario;
	}

	public IStatus execute( IProgressMonitor monitor, IAdaptable adaptable ){
		//Check wether the current dynamic Web Project is properly build to invoke web service
//		Properties properties = new Properties();
//		try {
//			properties.load(new FileInputStream(WSASCoreUtils.tempRuntimeStatusFileLocation()));
//			if (properties.containsKey(WSASCoreUIMessages.PROPERTY_KEY_STATUS)){
//				 status = Status.OK_STATUS;
//				 model.setServerStatus(true);
//			}else{
//				status = StatusUtils.errorStatus(WSASCoreUIMessages.ERROR_SERVER_IS_NOT_SET);
//			}
//		} catch (FileNotFoundException e) {
//			status = StatusUtils.errorStatus(WSASCoreUIMessages.ERROR_INVALID_FILE_READ_WRITEL+
//												WSASCoreUIMessages.ERROR_SERVER_IS_NOT_SET);
//		} catch (IOException e) {
//			status = StatusUtils.errorStatus(WSASCoreUIMessages.ERROR_INVALID_FILE_READ_WRITEL+
//												WSASCoreUIMessages.ERROR_SERVER_IS_NOT_SET);
//		}
		 status = Status.OK_STATUS;
		 model.setServerStatus(true);
		ServiceContext serviceContext = ServiceContext.getInstance();
		if (scenario == WebServiceScenario.TOPDOWN) {
			model.setWsdlURI(ws.getWebServiceInfo().getWsdlURL());
			model.setDatabindingType(WSASCoreUIMessages.DATA_BINDING_ADB);
			DefaultCodegenUtil defaultCodegenUtil = new DefaultCodegenUtil(model);
			defaultCodegenUtil.populateModelParamsFromWSDL();
			model.setServicesXML(true);
			model.setServerXMLCheck(true);
			serviceContext.setServiceName(model.getServiceName());
		}else if (scenario == WebServiceScenario.BOTTOMUP) {
			model.setServiceClass(ws.getWebServiceInfo().getImplURL());
			model.setServerInstanceID(ws.getWebServiceInfo().getServerInstanceId());
			//set the service name inside BUServiceContext for used by client if invoke together
			serviceContext.setServiceName(
					CommonUtils.classNameFromQualifiedName(ws.getWebServiceInfo().getImplURL())
					);

			model.setGenerateServicesXML(true);
		}else{
			//never come here
		}
		serviceContext.addServiceToProjectMap(serviceContext.getServiceName(), model.getWebProjectName());

		// Fix for the Bugzilla Bug 175030
		// Axis2: WSDL representing Web service not passed to Axis2 client
		// After setting the initial wsdlURL return from the framework to the data model,
		// replace it with the deployed wsdlURL
		String deployedWSDLURL = FacetContainerUtils.getDeployedWSDLURL(
					model.getWebProjectName(),
					serviceContext.getServiceName());
		ws.getWebServiceInfo().setWsdlURL(deployedWSDLURL);

		WSASEmitterContext context = WebServiceWSASCorePlugin.getDefault().getWSASEmitterContext();

		System.setProperty("javax.net.ssl.trustStore", context.getWSASRuntimeLocation()+File.separator+"conf"+File.separator+"wso2wsas.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "wso2wsas");
        System.setProperty("javax.net.ssl.trustStoreType","wso2wsas");

		return status;
	}

	public DataModel getWebServiceDataModel()
	{
		return model;
	}
}


text:
import scipy.sparse as sp

from .sparsefuncs_fast import (csr_mean_variance_axis0,
                               csc_mean_variance_axis0,
                               inplace_csr_column_scale,
                               inplace_csc_column_scale)

def mean_variance_axis0(X):
    """Compute mean and variance along axis 0 on a CSR or CSC matrix

    Parameters
    ----------
    X: CSR or CSC sparse matrix, shape (n_samples, n_features)
        Input data.

    Returns
    -------

    means: float array with shape (n_features,)
        Feature-wise means

    variances: float array with shape (n_features,)
        Feature-wise variances

    """
    if isinstance(X, sp.csr_matrix):
        return csr_mean_variance_axis0(X)
    elif isinstance(X, sp.csc_matrix):
        return csc_mean_variance_axis0(X)
    else:
        raise TypeError(
                "Unsupported type; expected a CSR or CSC sparse matrix.")

def inplace_column_scale(X, scale):
    """Inplace column scaling of a CSC/CSR matrix.

    Scale each feature of the data matrix by multiplying with specific scale
    provided by the caller assuming a (n_samples, n_features) shape.

    Parameters
    ----------
    X: CSC or CSR matrix with shape (n_samples, n_features)
        Matrix to normalize using the variance of the features.

    scale: float array with shape (n_features,)
        Array of precomputed feature-wise values to use for scaling.
    """
    if isinstance(X, sp.csr_matrix):
        return inplace_csr_column_scale(X, scale)
    elif isinstance(X, sp.csc_matrix):
        return inplace_csc_column_scale(X, scale)
    else:
        raise TypeError(
                "Unsupported type; expected a CSR or CSC sparse matrix.")


text:
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Containers.Tests
{
    using System;
    using ExtensionsDependencyInjectionIntegration;
    using Microsoft.Extensions.DependencyInjection;
    using Saga;
    using Scenarios;

    public class ExtensionsDependencyInjectionIntegration_Consumer :
        When_registering_a_consumer
    {
        readonly IServiceProvider _services;

        public ExtensionsDependencyInjectionIntegration_Consumer()
        {
            var collection = new ServiceCollection();

            collection.AddScoped<SimpleConsumer>();

            collection.AddMassTransit(x =>
            {
                x.AddConsumer<SimpleConsumer>();
            });

            collection.AddScoped<ISimpleConsumerDependency, SimpleConsumerDependency>();
            collection.AddScoped<AnotherMessageConsumer, AnotherMessageConsumerImpl>();

            _services = collection.BuildServiceProvider();
        }

        protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
        {
            configurator.LoadFrom(_services);
        }
    }

    public class ExtensionsDependencyInjectionIntegration_Saga :
        When_registering_a_saga
    {
        readonly IServiceProvider _services;

        public ExtensionsDependencyInjectionIntegration_Saga()
        {
            var collection = new ServiceCollection();

            collection.AddMassTransit(x =>
            {
                x.AddSaga<SimpleSaga>();
            });

            collection.AddSingleton<ISagaRepository<SimpleSaga>,  InMemorySagaRepository<SimpleSaga>>();

            _services = collection.BuildServiceProvider();
        }

        protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
        {
            configurator.LoadFrom(_services);
        }

        protected override ISagaRepository<T> GetSagaRepository<T>()
        {
            return _services.GetService<ISagaRepository<T>>();
        }
    }
}


text:
require 'helper'

class TestArel < Test::Unit::TestCase
  def setup
    @postgres = init_postgres
    @sqlite3  = init_sqlite3
    @mysql    = init_mysql
  end

  def test_01_construction
    assert_kind_of(RDBI::Arel, @sqlite3)
    assert_kind_of(RDBI::Arel, @postgres)
    assert_kind_of(RDBI::Arel, @mysql)

    assert_kind_of(Arel::Table, @sqlite3[:foo])
    assert_kind_of(Arel::Table, @sqlite3.foo)
    assert_kind_of(Arel::Table, @postgres[:foo])
    assert_kind_of(Arel::Table, @postgres.foo)
    assert_kind_of(Arel::Table, @mysql[:foo])
    assert_kind_of(Arel::Table, @mysql.foo)
  end

  def test_02_composition
    assert_kind_of(Arel::SelectManager, @sqlite3.foo.project(Arel.sql("*")))
    assert_kind_of(Arel::SelectManager, @postgres.foo.project(Arel.sql("*")))
    assert_kind_of(Arel::SelectManager, @mysql.foo.project(Arel.sql("*")))

    assert_kind_of(Arel::SelectManager, @sqlite3.foo.where(@sqlite3.foo[:foo].eq("stuff")))
    assert_kind_of(Arel::SelectManager, @postgres.foo.where(@postgres.foo[:foo].eq("stuff")))
    assert_kind_of(Arel::SelectManager, @mysql.foo.where(@mysql.foo[:foo].eq("stuff")))
  end

  def test_03_sql_basic_select
    assert_equal(
      @sqlite3[:foo].project(Arel.sql("*")).where(@sqlite3[:foo][:id].eq('stuff')).to_sql,
      %q[SELECT * FROM "foo"  WHERE "foo"."id" = 'stuff']
    )

    assert_equal(
      @postgres[:foo].project(Arel.sql("*")).where(@postgres[:foo][:id].eq('stuff')).to_sql,
      %q[SELECT * FROM "foo"  WHERE "foo"."id" = E'stuff']
    )

    assert_equal(
      @mysql[:foo].project(Arel.sql("*")).where(@mysql[:foo][:id].eq('stuff')).to_sql,
      %q[SELECT * FROM "foo"  WHERE "foo"."id" = 'stuff']
    )
  end

  def test_04_join
    assert_equal(
      @sqlite3[:foo].project(Arel.sql("*")).join(@sqlite3[:bar]).on(@sqlite3[:bar][:id].eq(@sqlite3[:foo][:id])).to_sql,
      %q[SELECT * FROM "foo" INNER JOIN "bar" ON "bar"."id" = "foo"."id"]
    )

    assert_equal(
      @postgres[:foo].project(Arel.sql("*")).join(@postgres[:bar]).on(@postgres[:bar][:id].eq(@postgres[:foo][:id])).to_sql,
      %q[SELECT * FROM "foo" INNER JOIN "bar" ON "bar"."id" = "foo"."id"]
    )

    assert_equal(
      @mysql[:foo].project(Arel.sql("*")).join(@mysql[:bar]).on(@mysql[:bar][:id].eq(@mysql[:foo][:id])).to_sql,
      %q[SELECT * FROM "foo" INNER JOIN "bar" ON "bar"."id" = "foo"."id"]
    )
  end

  def teardown
    [ @postgres, @sqlite3, @mysql ].each(&:disconnect)
  end
end


text:
package profile_test

import (
	"fmt"
	"log"

	"context"

	"time"

	"github.com/PhilipBorgesen/minecraft/profile"
)

// The following example shows how to retrieve and report all information about
// a Minecraft profile based on its username.
func Example() {
	ctx := context.TODO()

	// User to retrieve information about
	const username = "nergalic"

	// Retrieve basic information
	p, err := profile.Load(ctx, username)
	if err != nil {
		log.Fatalf("Failed to load profile: %s", err)
	}

	// Get case-corrected username and ID
	name, id := p.Name, p.ID

	// Load previously associated usernames
	hist, err := p.LoadNameHistory(ctx, false)
	if err != nil {
		log.Fatalf("Failed to load profile name history: %s", err)
	}

	// Load cape, skin and model type
	props, err := p.LoadProperties(ctx, false)
	if err != nil {
		log.Fatalf("Failed to load profile properties: %s", err)
	}

	// Get model type, skin and cape
	model, skin, cape := props.Model, props.SkinURL, props.CapeURL

	// If profile has no custom skin
	if skin == "" {
		skin = "<NONE>"
	}

	// If profile has no cape
	if cape == "" {
		cape = "<NONE>"
	}

	// Report information
	fmt.Printf("INFORMATION FOR:         %32s\n", username)
	fmt.Println("---------------------------------------------------------")
	fmt.Printf("CASE-CORRECTED USERNAME: %32s\n", name)
	fmt.Printf("ID:                      %32s\n", id)
	fmt.Printf("PRIOR NAMES:             %32s\n", fmt.Sprint(hist))
	fmt.Println()
	fmt.Printf("SKIN MODEL:              %32s\n", model)
	fmt.Printf("SKIN URL:                %32s\n", skin)
	fmt.Printf("CAPE URL:                %32s\n", cape)
	// output:
	// INFORMATION FOR:                                 nergalic
	// ---------------------------------------------------------
	// CASE-CORRECTED USERNAME:                         Nergalic
	// ID:                      087cc153c3434ff7ac497de1569affa1
	// PRIOR NAMES:                              [GeneralSezuan]
	//
	// SKIN MODEL:                                         Steve
	// SKIN URL:                http://textures.minecraft.net/texture/5b40f251f7c8db60943495db6bf54353102d6cad20d2299d5f973f36b4f3677e
	// CAPE URL:                                          <NONE>
}

// The following example shows how to retrieve a Minecraft profile based on the
// username it was registered under.
func ExampleLoadAtTime() {
	ctx := context.TODO()

	// Username the profile originally used
	const origUser = "GeneralSezuan"

	// Retrieve basic information of profile
	p, err := profile.LoadAtTime(ctx, origUser, time.Unix(0, 0))
	if err != nil {
		log.Fatalf("Failed to load profile: %s", err)
	}

	fmt.Println("Current username: " + p.Name)
	fmt.Println("      Profile ID: " + p.ID)
	// output:
	// Current username: Nergalic
	//       Profile ID: 087cc153c3434ff7ac497de1569affa1
}

// The following example demonstrates how to load basic information of multiple
// Minecraft profiles based on their currently associated usernames.
func ExampleLoadMany() {
	ctx := context.TODO()

	// Retrieve basic information of profiles that exist
	ps, err := profile.LoadMany(ctx, "nergalic", "breesakana", "doesNotExist")
	if err != nil {
		log.Fatalf("Failed to load profiles: %s", err)
	}

	for _, p := range ps {
		fmt.Printf("%-10s %s\n", p.Name, p.ID)
	}
	// Unordered output:
	// BreeSakana d9a5b542ce88442aaab38ec13e6c7773
	// Nergalic   087cc153c3434ff7ac497de1569affa1
}


text:
import { Reducer, Action } from 'redux';

const makeResetReducer = <ActionType extends string, State>(
  resetActionType: ActionType,
  reducer: Reducer<State>
) => (state: any, action: Action): State => {
  if (action.type === resetActionType) {
    return reducer(undefined, action);
  }
  return reducer(state, action);
};

export default makeResetReducer;


text:
package com.amazonaws.services.lexruntimev2.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class PutSessionRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The identifier of the bot that receives the session data.
     *

     */
    private String botId;
    /**
     *

     * The alias identifier of the bot that receives the session data.
     *

     */
    private String botAliasId;
    /**
     *

     * The locale where the session is in use.
     *

     */
    private String localeId;
    /**
     *

     * The identifier of the session that receives the session data.
     *

     */
    private String sessionId;
    /**
     *

     * A list of messages to send to the user. Messages are sent in the order that they are defined in the list.
     *

     */
    private java.util.List<Message> messages;
    /**
     *

     * Sets the state of the session with the user. You can use this to set the current intent, attributes, context, and
     * dialog action. Use the dialog action to determine the next step that Amazon Lex V2 should use in the conversation
     * with the user.
     *

     */
    private SessionState sessionState;
    /**
     *

     * Request-specific information passed between Amazon Lex V2 and the client application.
     *

     *

     * The namespace x-amz-lex: is reserved for special attributes. Don't create any request attributes
     * with the prefix x-amz-lex:.
     *

     */
    private java.util.Map<String, String> requestAttributes;
    /**
     *

     * The message that Amazon Lex V2 returns in the response can be either text or speech depending on the value of
     * this parameter.
     *

     *

     *

     *

     * If the value is text/plain; charset=utf-8, Amazon Lex V2 returns text in the response.
     *

     *

     *

     */
    private String responseContentType;

    /**
     *

     * The identifier of the bot that receives the session data.
     *

     *
     * @param botId
     *        The identifier of the bot that receives the session data.
     */

    public void setBotId(String botId) {
        this.botId = botId;
    }

    /**
     *

     * The identifier of the bot that receives the session data.
     *

     *
     * @return The identifier of the bot that receives the session data.
     */

    public String getBotId() {
        return this.botId;
    }

    /**
     *

     * The identifier of the bot that receives the session data.
     *

     *
     * @param botId
     *        The identifier of the bot that receives the session data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest withBotId(String botId) {
        setBotId(botId);
        return this;
    }

    /**
     *

     * The alias identifier of the bot that receives the session data.
     *

     *
     * @param botAliasId
     *        The alias identifier of the bot that receives the session data.
     */

    public void setBotAliasId(String botAliasId) {
        this.botAliasId = botAliasId;
    }

    /**
     *

     * The alias identifier of the bot that receives the session data.
     *

     *
     * @return The alias identifier of the bot that receives the session data.
     */

    public String getBotAliasId() {
        return this.botAliasId;
    }

    /**
     *

     * The alias identifier of the bot that receives the session data.
     *

     *
     * @param botAliasId
     *        The alias identifier of the bot that receives the session data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest withBotAliasId(String botAliasId) {
        setBotAliasId(botAliasId);
        return this;
    }

    /**
     *

     * The locale where the session is in use.
     *

     *
     * @param localeId
     *        The locale where the session is in use.
     */

    public void setLocaleId(String localeId) {
        this.localeId = localeId;
    }

    /**
     *

     * The locale where the session is in use.
     *

     *
     * @return The locale where the session is in use.
     */

    public String getLocaleId() {
        return this.localeId;
    }

    /**
     *

     * The locale where the session is in use.
     *

     *
     * @param localeId
     *        The locale where the session is in use.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest withLocaleId(String localeId) {
        setLocaleId(localeId);
        return this;
    }

    /**
     *

     * The identifier of the session that receives the session data.
     *

     *
     * @param sessionId
     *        The identifier of the session that receives the session data.
     */

    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }

    /**
     *

     * The identifier of the session that receives the session data.
     *

     *
     * @return The identifier of the session that receives the session data.
     */

    public String getSessionId() {
        return this.sessionId;
    }

    /**
     *

     * The identifier of the session that receives the session data.
     *

     *
     * @param sessionId
     *        The identifier of the session that receives the session data.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest withSessionId(String sessionId) {
        setSessionId(sessionId);
        return this;
    }

    /**
     *

     * A list of messages to send to the user. Messages are sent in the order that they are defined in the list.
     *

     *
     * @return A list of messages to send to the user. Messages are sent in the order that they are defined in the list.
     */

    public java.util.List<Message> getMessages() {
        return messages;
    }

    /**
     *

     * A list of messages to send to the user. Messages are sent in the order that they are defined in the list.
     *

     *
     * @param messages
     *        A list of messages to send to the user. Messages are sent in the order that they are defined in the list.
     */

    public void setMessages(java.util.Collection<Message> messages) {
        if (messages == null) {
            this.messages = null;
            return;
        }

        this.messages = new java.util.ArrayList<Message>(messages);
    }

    /**
     *

     * A list of messages to send to the user. Messages are sent in the order that they are defined in the list.
     *

     *

     * NOTE: This method appends the values to the existing list (if any). Use
     * {@link #setMessages(java.util.Collection)} or {@link #withMessages(java.util.Collection)} if you want to override
     * the existing values.
     *

     *
     * @param messages
     *        A list of messages to send to the user. Messages are sent in the order that they are defined in the list.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest withMessages(Message... messages) {
        if (this.messages == null) {
            setMessages(new java.util.ArrayList<Message>(messages.length));
        }
        for (Message ele : messages) {
            this.messages.add(ele);
        }
        return this;
    }

    /**
     *

     * A list of messages to send to the user. Messages are sent in the order that they are defined in the list.
     *

     *
     * @param messages
     *        A list of messages to send to the user. Messages are sent in the order that they are defined in the list.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest withMessages(java.util.Collection<Message> messages) {
        setMessages(messages);
        return this;
    }

    /**
     *

     * Sets the state of the session with the user. You can use this to set the current intent, attributes, context, and
     * dialog action. Use the dialog action to determine the next step that Amazon Lex V2 should use in the conversation
     * with the user.
     *

     *
     * @param sessionState
     *        Sets the state of the session with the user. You can use this to set the current intent, attributes,
     *        context, and dialog action. Use the dialog action to determine the next step that Amazon Lex V2 should use
     *        in the conversation with the user.
     */

    public void setSessionState(SessionState sessionState) {
        this.sessionState = sessionState;
    }

    /**
     *

     * Sets the state of the session with the user. You can use this to set the current intent, attributes, context, and
     * dialog action. Use the dialog action to determine the next step that Amazon Lex V2 should use in the conversation
     * with the user.
     *

     *
     * @return Sets the state of the session with the user. You can use this to set the current intent, attributes,
     *         context, and dialog action. Use the dialog action to determine the next step that Amazon Lex V2 should
     *         use in the conversation with the user.
     */

    public SessionState getSessionState() {
        return this.sessionState;
    }

    /**
     *

     * Sets the state of the session with the user. You can use this to set the current intent, attributes, context, and
     * dialog action. Use the dialog action to determine the next step that Amazon Lex V2 should use in the conversation
     * with the user.
     *

     *
     * @param sessionState
     *        Sets the state of the session with the user. You can use this to set the current intent, attributes,
     *        context, and dialog action. Use the dialog action to determine the next step that Amazon Lex V2 should use
     *        in the conversation with the user.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest withSessionState(SessionState sessionState) {
        setSessionState(sessionState);
        return this;
    }

    /**
     *

     * Request-specific information passed between Amazon Lex V2 and the client application.
     *

     *

     * The namespace x-amz-lex: is reserved for special attributes. Don't create any request attributes
     * with the prefix x-amz-lex:.
     *

     *
     * @return Request-specific information passed between Amazon Lex V2 and the client application.

     *

     *         The namespace x-amz-lex: is reserved for special attributes. Don't create any request
     *         attributes with the prefix x-amz-lex:.
     */

    public java.util.Map<String, String> getRequestAttributes() {
        return requestAttributes;
    }

    /**
     *

     * Request-specific information passed between Amazon Lex V2 and the client application.
     *

     *

     * The namespace x-amz-lex: is reserved for special attributes. Don't create any request attributes
     * with the prefix x-amz-lex:.
     *

     *
     * @param requestAttributes
     *        Request-specific information passed between Amazon Lex V2 and the client application.

     *

     *        The namespace x-amz-lex: is reserved for special attributes. Don't create any request
     *        attributes with the prefix x-amz-lex:.
     */

    public void setRequestAttributes(java.util.Map<String, String> requestAttributes) {
        this.requestAttributes = requestAttributes;
    }

    /**
     *

     * Request-specific information passed between Amazon Lex V2 and the client application.
     *

     *

     * The namespace x-amz-lex: is reserved for special attributes. Don't create any request attributes
     * with the prefix x-amz-lex:.
     *

     *
     * @param requestAttributes
     *        Request-specific information passed between Amazon Lex V2 and the client application.

     *

     *        The namespace x-amz-lex: is reserved for special attributes. Don't create any request
     *        attributes with the prefix x-amz-lex:.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest withRequestAttributes(java.util.Map<String, String> requestAttributes) {
        setRequestAttributes(requestAttributes);
        return this;
    }

    /**
     * Add a single RequestAttributes entry
     *
     * @see PutSessionRequest#withRequestAttributes
     * @returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest addRequestAttributesEntry(String key, String value) {
        if (null == this.requestAttributes) {
            this.requestAttributes = new java.util.HashMap<String, String>();
        }
        if (this.requestAttributes.containsKey(key))
            throw new IllegalArgumentException("Duplicated keys (" + key.toString() + ") are provided.");
        this.requestAttributes.put(key, value);
        return this;
    }

    /**
     * Removes all the entries added into RequestAttributes.
     *
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest clearRequestAttributesEntries() {
        this.requestAttributes = null;
        return this;
    }

    /**
     *

     * The message that Amazon Lex V2 returns in the response can be either text or speech depending on the value of
     * this parameter.
     *

     *

     *

     *

     * If the value is text/plain; charset=utf-8, Amazon Lex V2 returns text in the response.
     *

     *

     *

     *
     * @param responseContentType
     *        The message that Amazon Lex V2 returns in the response can be either text or speech depending on the value
     *        of this parameter.

     *

     *

     *

     *        If the value is text/plain; charset=utf-8, Amazon Lex V2 returns text in the response.
     *

     *

     */

    public void setResponseContentType(String responseContentType) {
        this.responseContentType = responseContentType;
    }

    /**
     *

     * The message that Amazon Lex V2 returns in the response can be either text or speech depending on the value of
     * this parameter.
     *

     *

     *

     *

     * If the value is text/plain; charset=utf-8, Amazon Lex V2 returns text in the response.
     *

     *

     *

     *
     * @return The message that Amazon Lex V2 returns in the response can be either text or speech depending on the
     *         value of this parameter.

     *

     *

     *

     *         If the value is text/plain; charset=utf-8, Amazon Lex V2 returns text in the response.
     *

     *

     */

    public String getResponseContentType() {
        return this.responseContentType;
    }

    /**
     *

     * The message that Amazon Lex V2 returns in the response can be either text or speech depending on the value of
     * this parameter.
     *

     *

     *

     *

     * If the value is text/plain; charset=utf-8, Amazon Lex V2 returns text in the response.
     *

     *

     *

     *
     * @param responseContentType
     *        The message that Amazon Lex V2 returns in the response can be either text or speech depending on the value
     *        of this parameter.

     *

     *

     *

     *        If the value is text/plain; charset=utf-8, Amazon Lex V2 returns text in the response.
     *

     *

     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public PutSessionRequest withResponseContentType(String responseContentType) {
        setResponseContentType(responseContentType);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getBotId() != null)
            sb.append("BotId: ").append(getBotId()).append(",");
        if (getBotAliasId() != null)
            sb.append("BotAliasId: ").append(getBotAliasId()).append(",");
        if (getLocaleId() != null)
            sb.append("LocaleId: ").append(getLocaleId()).append(",");
        if (getSessionId() != null)
            sb.append("SessionId: ").append(getSessionId()).append(",");
        if (getMessages() != null)
            sb.append("Messages: ").append(getMessages()).append(",");
        if (getSessionState() != null)
            sb.append("SessionState: ").append(getSessionState()).append(",");
        if (getRequestAttributes() != null)
            sb.append("RequestAttributes: ").append(getRequestAttributes()).append(",");
        if (getResponseContentType() != null)
            sb.append("ResponseContentType: ").append(getResponseContentType());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof PutSessionRequest == false)
            return false;
        PutSessionRequest other = (PutSessionRequest) obj;
        if (other.getBotId() == null ^ this.getBotId() == null)
            return false;
        if (other.getBotId() != null && other.getBotId().equals(this.getBotId()) == false)
            return false;
        if (other.getBotAliasId() == null ^ this.getBotAliasId() == null)
            return false;
        if (other.getBotAliasId() != null && other.getBotAliasId().equals(this.getBotAliasId()) == false)
            return false;
        if (other.getLocaleId() == null ^ this.getLocaleId() == null)
            return false;
        if (other.getLocaleId() != null && other.getLocaleId().equals(this.getLocaleId()) == false)
            return false;
        if (other.getSessionId() == null ^ this.getSessionId() == null)
            return false;
        if (other.getSessionId() != null && other.getSessionId().equals(this.getSessionId()) == false)
            return false;
        if (other.getMessages() == null ^ this.getMessages() == null)
            return false;
        if (other.getMessages() != null && other.getMessages().equals(this.getMessages()) == false)
            return false;
        if (other.getSessionState() == null ^ this.getSessionState() == null)
            return false;
        if (other.getSessionState() != null && other.getSessionState().equals(this.getSessionState()) == false)
            return false;
        if (other.getRequestAttributes() == null ^ this.getRequestAttributes() == null)
            return false;
        if (other.getRequestAttributes() != null && other.getRequestAttributes().equals(this.getRequestAttributes()) == false)
            return false;
        if (other.getResponseContentType() == null ^ this.getResponseContentType() == null)
            return false;
        if (other.getResponseContentType() != null && other.getResponseContentType().equals(this.getResponseContentType()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getBotId() == null) ? 0 : getBotId().hashCode());
        hashCode = prime * hashCode + ((getBotAliasId() == null) ? 0 : getBotAliasId().hashCode());
        hashCode = prime * hashCode + ((getLocaleId() == null) ? 0 : getLocaleId().hashCode());
        hashCode = prime * hashCode + ((getSessionId() == null) ? 0 : getSessionId().hashCode());
        hashCode = prime * hashCode + ((getMessages() == null) ? 0 : getMessages().hashCode());
        hashCode = prime * hashCode + ((getSessionState() == null) ? 0 : getSessionState().hashCode());
        hashCode = prime * hashCode + ((getRequestAttributes() == null) ? 0 : getRequestAttributes().hashCode());
        hashCode = prime * hashCode + ((getResponseContentType() == null) ? 0 : getResponseContentType().hashCode());
        return hashCode;
    }

    @Override
    public PutSessionRequest clone() {
        return (PutSessionRequest) super.clone();
    }

}


text:
using System;
using System.Linq;
using System.Text;
using Nimbus.Configuration.Settings;
using Nimbus.InfrastructureContracts.Routing;

namespace Nimbus.Infrastructure
{
    internal class PathFactory : IPathFactory
    {
        internal const int MaxPathLength = 260;
        internal const int MaxNameLength = 50;

        private const string _queuePrefix = "q";
        private const string _topicPrefix = "t";
        private const string _instanceInputQueuePrefix = "inputqueue";
        private const string _deadLetterOfficePath = "deadletteroffice";

        // Entity segments can contain only letters, numbers, periods (.), hyphens (-), and underscores.
        private const string _queueCharacterWhitelist = "abcdefghijklmnopqrstuvwxyz1234567890.-";

        private readonly string _globalPrefix;

        public PathFactory(GlobalPrefixSetting globalPrefix)
        {
            _globalPrefix = (globalPrefix.Value == string.Empty)
                ? string.Empty
                : $"{globalPrefix.Value}.";
        }

        public string InputQueuePathFor(string applicationName, string instanceName)
        {
            var unsanitizedPath = $"{_globalPrefix}{_instanceInputQueuePrefix}.{applicationName}.{instanceName}";
            var sanitizedPath = Sanitize(unsanitizedPath);
            var path = Shorten(sanitizedPath, MaxPathLength);
            return path;
        }

        public string QueuePathFor(Type type)
        {
            var typeName = StripGenericQualification(type);
            var unsanitizedPath = $"{_globalPrefix}{_queuePrefix}.{typeName}";
            var sanitizedPath = Sanitize(unsanitizedPath);
            var path = Shorten(sanitizedPath, MaxPathLength);
            return path;
        }

        public string TopicPathFor(Type type)
        {
            var typeName = StripGenericQualification(type);
            var unsanitizedPath = $"{_globalPrefix}{_topicPrefix}.{typeName}";
            var sanitizedPath = Sanitize(unsanitizedPath);
            var path = Shorten(sanitizedPath, MaxPathLength);
            return path;
        }

        public string SubscriptionNameFor(string applicationName, Type handlerType)
        {
            var unsanitizedName = $"{applicationName}.{handlerType.Name}";
            var sanitizedName = Sanitize(unsanitizedName);
            var name = Shorten(sanitizedName, MaxNameLength);
            return name;
        }

        public string SubscriptionNameFor(string applicationName, string instanceName, Type handlerType)
        {
            var unsanitizedName = $"{applicationName}.{instanceName}.{handlerType.Name}";
            var sanitizedName = Sanitize(unsanitizedName);
            var name = Shorten(sanitizedName, MaxNameLength);
            return name;
        }

        public string DeadLetterOfficePath()
        {
            var unsanitizedPath = $"{_globalPrefix}{_deadLetterOfficePath}";
            var sanitizedPath = Sanitize(unsanitizedPath);
            var path = Shorten(sanitizedPath, MaxPathLength);
            return path;
        }

        private static string StripGenericQualification(Type type)
        {
            if (!type.IsGenericType) return type.FullName;

            var genericArgs = type.GetGenericArguments().Select(arg => arg.Name);

            return type.Namespace + "." + type.Name + "-" + string.Join("-", genericArgs);
        }

        private static string Sanitize(string path)
        {
            path = string.Join("", path.ToLower().ToCharArray().Select(SanitiseCharacter));
            return path;
        }

        internal static string Shorten(string path, int maxLength)
        {
            if (path.Length <= maxLength)
                return path;

            var hash = CalculateAdler32Hash(path);

            var shortPath = path.Substring(0, maxLength - hash.Length) + hash;
            return shortPath;
        }

        private static char SanitiseCharacter(char currentChar)
        {
            var whiteList = _queueCharacterWhitelist.ToCharArray();

            if (!whiteList.Contains(currentChar))
                return '.';

            return currentChar;
        }

        private static string CalculateAdler32Hash(string inputString)
        {
            const uint BASE = 65521;
            var buffer = Encoding.UTF8.GetBytes(inputString);
            uint checksum = 1;
            var offset = 0;
            var count = buffer.Length;

            var s1 = checksum & 0xFFFF;
            var s2 = checksum >> 16;

            while (count > 0)
            {
                var n = 3800;
                if (n > count)
                {
                    n = count;
                }
                count -= n;
                while (--n >= 0)
                {
                    s1 = s1 + (uint) (buffer[offset++] & 0xff);
                    s2 = s2 + s1;
                }
                s1 %= BASE;
                s2 %= BASE;
            }

            checksum = (s2 << 16) | s1;
            return checksum.ToString();
        }
    }
}


text:
SELECT
    geometrie,
    forstkreis,
    forstrevier,
    schutzwald_nr1,
    schutzwald_nr2,
    sturz,
    rutsch,
    gerinnerelevante_prozesse,
    lawine,
    andere_kt,
    objektkategorie,
    schadenpotential,
    hauptgefahrenpotential,
    intensitaet_geschaetzt,
    bemerkungen,
    gemeinde,
    (flaeche::float / 10000) AS flaeche
FROM
    awjf_schutzwald_v1.schutzwald
;


text:
@interface QCFriendViewController : UIViewController

@end


text:
package RE.blocks;

import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Icon;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import RE.RealElectricity;
import RE.tileentities.TileEntitySolarPanel;
import cpw.mods.fml.common.network.FMLNetworkHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class BlockSolarPanel extends BlockContainer {

	protected BlockSolarPanel(int id) {
		super(id, Material.rock);

		setCreativeTab(RealElectricity.creativeTab);
		setHardness(2F);
		setStepSound(soundStoneFootstep);
		setUnlocalizedName(BlockInfo.SOLARPANEL_UNLOCALIZED_NAME);
	}

	@Override
	public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer entityPlayer, int side, float hitX, float hitY, float hitZ) {
		if (!world.isRemote) {
			FMLNetworkHandler.openGui(entityPlayer, RealElectricity.instance, 1, world, x, y, z);
		}

		return true;
	}

	@SideOnly(Side.CLIENT)
	private Icon topIcon;
	@SideOnly(Side.CLIENT)
	private Icon bottomIcon;
	@SideOnly(Side.CLIENT)
	private Icon sideIcon;

	@SideOnly(Side.CLIENT)
	@Override
	public void registerIcons(IconRegister register) {
		topIcon = register.registerIcon(BlockInfo.TEXTURE_LOCATION + ":" + BlockInfo.SOLARPANEL_TOP_ICON);
		bottomIcon = register.registerIcon(BlockInfo.TEXTURE_LOCATION + ":" + BlockInfo.WIRE_ATTACHMENT_ICON);
		sideIcon = register.registerIcon(BlockInfo.TEXTURE_LOCATION + ":" + BlockInfo.SOLARPANEL_SIDE_ICON);
	}

	@SideOnly(Side.CLIENT)
	@Override
	public Icon getIcon(int side, int meta) {
		if (side == 0) { // Bottom
			return bottomIcon;
		} else if (side == 1) { // Top
			return topIcon;
		}

		return sideIcon;
	}

	@Override
	public TileEntity createNewTileEntity(World world) {
		return new TileEntitySolarPanel();
	}

	@Override
	public void breakBlock(World world, int x, int y, int z, int id, int meta) {
		TileEntity te = world.getBlockTileEntity(x, y, z);
		if (te != null && te instanceof TileEntitySolarPanel) {
			IInventory inventory = (IInventory) te;

			for (int i = 0; i < inventory.getSizeInventory(); i++) {
				ItemStack itemstack = inventory.getStackInSlotOnClosing(i);

				if (itemstack != null) {
					float spawnX = x + world.rand.nextFloat();
					float spawnY = y + world.rand.nextFloat();
					float spawnZ = z + world.rand.nextFloat();

					EntityItem droppedItem = new EntityItem(world, spawnX, spawnY, spawnZ, itemstack);

					float mult = 0.05F;

					droppedItem.motionX = (-0.5F + world.rand.nextFloat()) * mult;
					droppedItem.motionY = (4F + world.rand.nextFloat()) * mult;
					droppedItem.motionZ = (-0.5F + world.rand.nextFloat()) * mult;

					world.spawnEntityInWorld(droppedItem);
				}
			}
		}

		super.breakBlock(world, x, y, z, id, meta);
	}

}


text:
Input::
//// [/user/username/projects/myproject/client/folder1/module1.ts]
export class Module1Class { }

//// [/user/username/projects/myproject/folder2/module2.ts]
import * as M from "folder1/module1";

//// [/user/username/projects/myproject/client/linktofolder2] symlink(/user/username/projects/myproject/folder2)
//// [/user/username/projects/myproject/tsconfig.json]
{"compilerOptions":{"baseUrl":"client","paths":{"*":["*"]}},"include":["client/**/*","folder2"]}

//// [/a/lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }

/a/lib/tsc.js -w -p . --extendedDiagnostics
Output::
[12:00:31 AM] Starting compilation in watch mode...

Current directory: /user/username/projects/myproject CaseSensitiveFileNames: false
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/tsconfig.json 2000 undefined Config file
Synchronizing program
CreatingProgramWith::
  roots: ["/user/username/projects/myproject/client/folder1/module1.ts","/user/username/projects/myproject/client/linktofolder2/module2.ts"]
  options: {"baseUrl":"/user/username/projects/myproject/client","paths":{"*":["*"]},"pathsBasePath":"/user/username/projects/myproject","watch":true,"project":"/user/username/projects/myproject","extendedDiagnostics":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"}
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/client/folder1/module1.ts 250 undefined Source file
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/client/linktofolder2/module2.ts 250 undefined Source file
FileWatcher:: Added:: WatchInfo: /a/lib/lib.d.ts 250 undefined Source file
DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
Elapsed:: *ms DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/node_modules/@types 1 undefined Type roots
[12:00:37 AM] Found 0 errors. Watching for file changes.

DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/client 1 undefined Wild card directory
Elapsed:: *ms DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/client 1 undefined Wild card directory
DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/folder2 1 undefined Wild card directory
Elapsed:: *ms DirectoryWatcher:: Added:: WatchInfo: /user/username/projects/myproject/folder2 1 undefined Wild card directory

Program root files: ["/user/username/projects/myproject/client/folder1/module1.ts","/user/username/projects/myproject/client/linktofolder2/module2.ts"]
Program options: {"baseUrl":"/user/username/projects/myproject/client","paths":{"*":["*"]},"pathsBasePath":"/user/username/projects/myproject","watch":true,"project":"/user/username/projects/myproject","extendedDiagnostics":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"}
Program structureReused: Not
Program files::
/a/lib/lib.d.ts
/user/username/projects/myproject/client/folder1/module1.ts
/user/username/projects/myproject/client/linktofolder2/module2.ts

Semantic diagnostics in builder refreshed for::
/a/lib/lib.d.ts
/user/username/projects/myproject/client/folder1/module1.ts
/user/username/projects/myproject/client/linktofolder2/module2.ts

Shape signatures in builder refreshed for::
/a/lib/lib.d.ts (used version)
/user/username/projects/myproject/client/folder1/module1.ts (used version)
/user/username/projects/myproject/client/linktofolder2/module2.ts (used version)

WatchedFiles::
/user/username/projects/myproject/tsconfig.json:
  {"fileName":"/user/username/projects/myproject/tsconfig.json","pollingInterval":250}
/user/username/projects/myproject/client/folder1/module1.ts:
  {"fileName":"/user/username/projects/myproject/client/folder1/module1.ts","pollingInterval":250}
/user/username/projects/myproject/client/linktofolder2/module2.ts:
  {"fileName":"/user/username/projects/myproject/client/linktofolder2/module2.ts","pollingInterval":250}
/a/lib/lib.d.ts:
  {"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
/user/username/projects/myproject/node_modules/@types:
  {"fileName":"/user/username/projects/myproject/node_modules/@types","pollingInterval":500}

FsWatches::

FsWatchesRecursive::
/user/username/projects/myproject/client:
  {"directoryName":"/user/username/projects/myproject/client"}
/user/username/projects/myproject/folder2:
  {"directoryName":"/user/username/projects/myproject/folder2"}

exitCode:: ExitStatus.undefined

//// [/user/username/projects/myproject/client/folder1/module1.js]
"use strict";
exports.__esModule = true;
exports.Module1Class = void 0;
var Module1Class = /** @class */ (function () {
    function Module1Class() {
    }
    return Module1Class;
}());
exports.Module1Class = Module1Class;

//// [/user/username/projects/myproject/folder2/module2.js]
"use strict";
exports.__esModule = true;

Change:: Add module3 to folder2

Input::
//// [/user/username/projects/myproject/folder2/module3.ts]
import * as M from "folder1/module1";

Output::
DirectoryWatcher:: Triggered with /user/username/projects/myproject/folder2/module3.ts :: WatchInfo: /user/username/projects/myproject/folder2 1 undefined Wild card directory
Scheduling update
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/folder2/module3.ts :: WatchInfo: /user/username/projects/myproject/folder2 1 undefined Wild card directory
Reloading new file names and options
Synchronizing program
[12:00:41 AM] File change detected. Starting incremental compilation...

CreatingProgramWith::
  roots: ["/user/username/projects/myproject/client/folder1/module1.ts","/user/username/projects/myproject/client/linktofolder2/module2.ts","/user/username/projects/myproject/client/linktofolder2/module3.ts"]
  options: {"baseUrl":"/user/username/projects/myproject/client","paths":{"*":["*"]},"pathsBasePath":"/user/username/projects/myproject","watch":true,"project":"/user/username/projects/myproject","extendedDiagnostics":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"}
FileWatcher:: Added:: WatchInfo: /user/username/projects/myproject/client/linktofolder2/module3.ts 250 undefined Source file
DirectoryWatcher:: Triggered with /user/username/projects/myproject/folder2/module3.js :: WatchInfo: /user/username/projects/myproject/folder2 1 undefined Wild card directory
Project: /user/username/projects/myproject/tsconfig.json Detected file add/remove of non supported extension: /user/username/projects/myproject/folder2/module3.js
Elapsed:: *ms DirectoryWatcher:: Triggered with /user/username/projects/myproject/folder2/module3.js :: WatchInfo: /user/username/projects/myproject/folder2 1 undefined Wild card directory
[12:00:45 AM] Found 0 errors. Watching for file changes.

Program root files: ["/user/username/projects/myproject/client/folder1/module1.ts","/user/username/projects/myproject/client/linktofolder2/module2.ts","/user/username/projects/myproject/client/linktofolder2/module3.ts"]
Program options: {"baseUrl":"/user/username/projects/myproject/client","paths":{"*":["*"]},"pathsBasePath":"/user/username/projects/myproject","watch":true,"project":"/user/username/projects/myproject","extendedDiagnostics":true,"configFilePath":"/user/username/projects/myproject/tsconfig.json"}
Program structureReused: Not
Program files::
/a/lib/lib.d.ts
/user/username/projects/myproject/client/folder1/module1.ts
/user/username/projects/myproject/client/linktofolder2/module2.ts
/user/username/projects/myproject/client/linktofolder2/module3.ts

Semantic diagnostics in builder refreshed for::
/user/username/projects/myproject/client/linktofolder2/module3.ts

Shape signatures in builder refreshed for::
/user/username/projects/myproject/client/linktofolder2/module3.ts (computed .d.ts)

WatchedFiles::
/user/username/projects/myproject/tsconfig.json:
  {"fileName":"/user/username/projects/myproject/tsconfig.json","pollingInterval":250}
/user/username/projects/myproject/client/folder1/module1.ts:
  {"fileName":"/user/username/projects/myproject/client/folder1/module1.ts","pollingInterval":250}
/user/username/projects/myproject/client/linktofolder2/module2.ts:
  {"fileName":"/user/username/projects/myproject/client/linktofolder2/module2.ts","pollingInterval":250}
/a/lib/lib.d.ts:
  {"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
/user/username/projects/myproject/node_modules/@types:
  {"fileName":"/user/username/projects/myproject/node_modules/@types","pollingInterval":500}
/user/username/projects/myproject/client/linktofolder2/module3.ts:
  {"fileName":"/user/username/projects/myproject/client/linktofolder2/module3.ts","pollingInterval":250}

FsWatches::

FsWatchesRecursive::
/user/username/projects/myproject/client:
  {"directoryName":"/user/username/projects/myproject/client"}
/user/username/projects/myproject/folder2:
  {"directoryName":"/user/username/projects/myproject/folder2"}

exitCode:: ExitStatus.undefined

//// [/user/username/projects/myproject/folder2/module3.js]
"use strict";
exports.__esModule = true;


text:
var MyProfile_P = Backbone.Model.extend({
	defaults: function() {
		return {
			nick: "empty ...",
			desc: "empty ...",
			mail: "empty ...",
			hashname: "empty..."
		};
	}
});
var my_profile_P=new MyProfile_P();
var MyProfileView_P = Backbone.View.extend({
	model:my_profile_P,
	el:$('#MyProfile_P'),
	// Cache the template function for a single item.
	template: _.template($('#MyProfile_P-template').html()),
	initialize: function() {
		this.listenTo(this.model, 'change', this.render);
	},
	render: function() {
		this.$el.html(this.template(this.model.toJSON()));
		return this;
	}
});
var MyProfileV_P=new MyProfileView_P;


text:
<?php

namespace Carew;

use Symfony\Component\Finder\SplFileInfo;

class Document
{
    const TYPE_POST = 'post';
    const TYPE_PAGE = 'page';
    const TYPE_API = 'api';
    const TYPE_UNKNOWN = 'unknown';

    private $body;
    private $bodyDecorated;
    private $file;
    private $filePath;
    private $layout;
    private $metadatas;
    private $navigations;
    private $path;
    private $published;
    private $tags;
    private $title;
    private $toc;
    private $type;
    private $vars;

    public function __construct(SplFileInfo $file = null, $filePath = null, $type = self::TYPE_UNKNOWN)
    {
        $this->file = $file;
        $this->filePath = $filePath;
        $this->type = $type;

        $this->layout = false;
        $this->published = true;
        $this->metadatas = array();
        $this->navigations = array();
        $this->tags = array();
        $this->toc = array();
        $this->vars = array();

        if ($file && is_file($file)) {
            $this->path = $file->getBaseName();
            $this->title = $file->getBaseName();
            $this->body = $this->bodyDecorated = file_get_contents($file);
        }
    }

    public function getBodyDecorated()
    {
        return $this->bodyDecorated;
    }

    public function setBodyDecorated($bodyDecorated)
    {
        $this->bodyDecorated = $bodyDecorated;

        return $this;
    }

    public function getBody()
    {
        return $this->body;
    }

    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

    public function getFile()
    {
        return $this->file;
    }

    public function getLayout()
    {
        return $this->layout;
    }

    public function setLayout($layout)
    {
        $this->layout = $layout;

        return $this;
    }

    public function getMetadatas()
    {
        return $this->metadatas;
    }

    public function addMetadatas(array $metadatas)
    {
        $this->metadatas = array_replace_recursive($this->metadatas, $metadatas);

        return $this;
    }

    public function getMetadata($key, $default = null)
    {
        return array_key_exists($key, $this->metadatas) ? $this->metadatas[$key] : $default;
    }

    public function setMetadata($key, $value)
    {
        $this->metadatas[$key] = $value;

        return $this;
    }

    public function getPath()
    {
        return $this->path;
    }

    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    public function getRootPath()
    {
        $path = ltrim($this->path, '/');
        if (0 === $nb = substr_count($path, DIRECTORY_SEPARATOR)) {
            return '.';
        }

        return rtrim(str_repeat('../', $nb), '/');
    }

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    public function getToc()
    {
        return $this->toc;
    }

    public function setToc($toc)
    {
        $this->toc = $toc;

        return $this;
    }

    public function getType()
    {
        return $this->type;
    }

    public function isTypePost()
    {
        return self::TYPE_POST == $this->type;
    }

    public function isTypePage()
    {
        return self::TYPE_PAGE == $this->type;
    }

    public function isTypeApi()
    {
        return self::TYPE_API == $this->type;
    }

    public function getVars()
    {
        return $this->vars;
    }

    public function getVar($key, $default = null)
    {
        return array_key_exists($key, $this->vars) ? $this->vars[$key] : $default;
    }

    public function setVars($vars)
    {
        $this->vars = $vars;

        return $this;
    }

    public function setVar($key, $value)
    {
        $this->vars[$key] = $value;

        return $this;
    }

    public function getFilePath()
    {
        return $this->filePath;
    }

    public function setFilePath($filePath)
    {
        $this->filePath = $filePath;

        return $this;
    }

    public function getNavigations()
    {
        return $this->navigations;
    }

    public function setNavigations($navigations)
    {
        if (!is_array($navigations)) {
            $navigations = array($navigations);
        }

        $this->navigations = $navigations;

        return $this;
    }

    public function getTags()
    {
        return $this->tags;
    }

    public function setTags($tags)
    {
        if (!is_array($tags)) {
            $tags = array($tags);
        }

        $this->tags = $tags;

        return $this;
    }

    public function __toString()
    {
        return $this->title;
    }

    public function isPublished()
    {
        return $this->published;
    }

    public function setPublished($published)
    {
        $this->published = $published;

        return $this;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>The Singleton</title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="viewport" content="width=device-width, initial-scale=0.6, maximum-scale=0.7, user-scalable=yes" />

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

    <link rel="stylesheet" href="app.css">
    <link rel="stylesheet" href="directives/quiz/kuizu.css">
    <link rel="stylesheet" href="bower_components/open-sans-fontface/open-sans.css">
    <link rel="stylesheet" href="bower_components/components-font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="assets/css/animate.css">
    <link rel="stylesheet" href="Home/Home.css">


text:
author: martin.ankerl@gmail.com
comments: true
date: 2006-01-25 04:33:46+00:00
layout: post
slug: software-design-principles
title: Software Design Principles
wordpress_id: 51
categories:
- programming
---

I have tried to collect the most important principles of software development. At least I consider them extremely important, I am sure that other people think otherwise. Good software designs should follow these principles as much as possible. Follow the links to learn more about the principles:

  * [DRY](http://www.artima.com/intv/dry.html) Don't Repeat Yourself
  * [PoLS](http://en.wikipedia.org/wiki/Principle_of_least_surprise) Principle of Least Surprise
  * [DTSTTCPW](http://c2.com/cgi/wiki?DoTheSimplestThingThatCouldPossiblyWork) Do The Simplest Thing That Could Possibly Work
  * [YAGNI](http://www.artima.com/weblogs/viewpost.jsp?thread=36529) You Aren't Gonna Need It

## DRY

Goes beyond code duplication. It says that each kind of information that you have to represent should be represented exactly once, that includes that there should be only one way to represent one kind of information. For example when you have an application that uses a database and define the database schema in the database, then in the application, then in wrapper classes. That's a load of stuff that highly depends on each other, and a big source of failures due to inconsistencies.

## PoLS

Probably is the most often ignored principle. Developers always try to solve complex problem, and most of the time they are so in love with their solutions to the problems that they do not care about the people that have to use their code. An excellent example is most about everything done in Java. For example, let's try to save a picture as a jpg image with a compression quality of 80%. This is the Java way:

```java
// Find a jpeg writer
ImageWriter writer = null;
Iterator iter = ImageIO.getImageWritersByFormatName("jpg");
if (iter.hasNext()) {
    writer = (ImageWriter) iter.next();
}

// Prepare output file
ImageOutputStream ios = ImageIO.createImageOutputStream(f);
writer.setOutput(ios);

// Set the compression quality
ImageWriteParam iwparam = new MyImageWriteParam();
iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwparam.setCompressionQuality(0.8);

// Write the image
writer.write(null, new IIOImage(img, null, null), iwparam);

// Cleanup
ios.flush();
writer.dispose();
ios.close();
```

One can immediately see that Java has a very flexible API that allows to do a lot of interesting stuff. But most of the time I do not want this complexity! This is how it is done if you try to follow the Principle of Least Surprise when designing your API, like [Ruby](http://www.ruby-lang.org/en/) tries to do:

```ruby
image.write('output.jpg') do
  self.compression = Magick::JPEGCompression
  self.quality = 80
end
```

I bet you can see the difference. This is exactly why technologies like J2EE are so complex and unmaintainable, because they ignore the PoLS.

## DTSTTCPW

Do The Simplest Thing That Could Possibly Work. If you implement functionality, do it as simple as possible. The code will be very readable, short and therefore maintainable because you can understand it quickly. It will also be less buggy. So do not try to be smart by writing complex code when it is not needed. Try to be smart by writing the simplest code possible, wich can actually be a very difficult task.

## YAGNI

Says that you should never implement functionality if you do not need it _right now_. That would be premature design, in most cases you will never need the functionality because requirements change too quickly, or you just guessed wrong. The quickest and most fail-save code is the code that does not exist - so don't code it if you are not absolutely sure you need it.

Together DTSTTCPW and YAGNI are very similar to KISS (Keep It Simple, Stupid), if not the same. DTSTTCPW says you should keep it simple, YAGNI says you should keep it stupid. But I think it is better to have these both principles to make it clearer what they mean. Be aware that in both DTSTTCPW and YAGNI you have to be able to easily refactor your program, because you need to add functionality when it is needed, and not earlier. Therefore you should have a good regression suite that [buys you confidence to allow for quickly refactoring](http://www.clarkware.com/articles/JUnitPrimer.html#usage) your code.


text:
using PlaceSystem.Data;
using PlaceSystem.Entities;
using PlaceSystem.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace PlaceSystem.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var context = new DataContext();
            var places = context.Places.Select(PlaceModel.FromPlace).ToList();
            var cities = context.Places.Select(x => x.City).Distinct().ToList();
            ViewBag.Cities = cities;
            return View(places);
        }

        public ActionResult Search(string cityBox, Category? categoryBox)
        {
            var context = new DataContext();
            var places = context.Places.Select(PlaceModel.FromPlace).ToList();

            if (string.IsNullOrWhiteSpace(cityBox) && !string.IsNullOrWhiteSpace(categoryBox.ToString()))
            {
                places = context.Places.Where(
                    x => x.Category == categoryBox).
                    Select(PlaceModel.FromPlace).ToList();
            }

            if (string.IsNullOrWhiteSpace(categoryBox.ToString()) && !string.IsNullOrWhiteSpace(cityBox))
            {
                places = context.Places.Where(
                    x => x.City.ToLower() == cityBox.ToLower()).
                    Select(PlaceModel.FromPlace).ToList();
            }

            if (!string.IsNullOrWhiteSpace(categoryBox.ToString()) && !string.IsNullOrWhiteSpace(cityBox))
            {
                places = context.Places.Where(
                    x => x.City.ToLower() == cityBox.ToLower() &&
                    x.Category == categoryBox).
                    Select(PlaceModel.FromPlace).ToList();
            }

            var cities = context.Places.Select(x => x.City).Distinct().ToList();
            ViewBag.Cities = cities;
            return View(places);
        }

        [Authorize]
        public ActionResult ByUser()
        {
            var user = this.HttpContext.User.Identity.Name;
            var context = new DataContext();
            var places = context.Places.Where(
                    x => x.UsersLiking.Any(u => u.UserName == user)).
                    Select(PlaceModel.FromPlace).ToList();

            var cities = context.Places.Select(x => x.City).Distinct().ToList();
            ViewBag.Cities = cities;
            return View(places);
        }

        public ActionResult Detail(int id)
        {
            var context = new DataContext();
            var place = context.Places.Where(x => x.Id == id)
                .Select(PlaceFullModel.FromPlace).FirstOrDefault();

            var cities = context.Places.Select(x => x.City).Distinct().ToList();
            ViewBag.Cities = cities;
            return View(place);
        }

        [Authorize]
        public ActionResult Like(int id)
        {
            var context = new DataContext();
            var place = context.Places.Where(x => x.Id == id).FirstOrDefault();
            var username = this.HttpContext.User.Identity.Name;
            var user = context.Users.Where(u => u.UserName == username).FirstOrDefault();
            place.UsersLiking.Add(user);
            context.SaveChanges();
            return RedirectToAction("ByUser");
        }

        [Authorize]
        public ActionResult Dislike(int id)
        {
            var context = new DataContext();
            var place = context.Places.Where(x => x.Id == id).FirstOrDefault();
            var username = this.HttpContext.User.Identity.Name;
            var user = context.Users.Where(u => u.UserName == username).FirstOrDefault();
            place.UsersLiking.Remove(user);
            context.SaveChanges();
            return RedirectToAction("ByUser");
        }

        [Authorize]
        public ActionResult Cancel()
        {
            return PartialView("_Empty");
        }

        [Authorize]
        public ActionResult Create(int placeId)
        {
            this.Session["placeId"] = placeId;
            return PartialView("_Create");
        }

        [Authorize]
        public ActionResult CreateOk(CommentModel model)
        {
            int placeId = (int)(this.Session["placeId"] ?? 0);
            if (ModelState.IsValid)
            {
                var context = new DataContext();
                var username = this.HttpContext.User.Identity.Name;
                var user = context.Users.Where(u => u.UserName == username).FirstOrDefault();
                var place = context.Places.Where(x => x.Id == placeId).FirstOrDefault();
                if (place == null)
                {
                    ModelState.AddModelError("Place", "Ivalid place id!");
                }

                if (user == null)
                {
                    ModelState.AddModelError("User", "Ivalid user!");
                }

                Comment comment = new Comment()
                {
                    Text = model.Text,
                    User = user
                };

                place.Comments.Add(comment);
                context.SaveChanges();

                return PartialView("_Success");
            }

            return PartialView("_Create", model);
        }
    }
}