text:
package amu.electrical.deptt;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.messaging.FirebaseMessaging;

import amu.electrical.deptt.fragment.FacultyFragment;
import amu.electrical.deptt.fragment.HomeFragment;
import amu.electrical.deptt.fragment.MessageFragment;

public class MainActivity extends AppCompatActivity {

    static {
        FirebaseMessaging.getInstance().subscribeToTopic("news");
        FirebaseDatabase.getInstance().setPersistenceEnabled(true);
    }

    private DrawerLayout mDrawerLayout;
    private HomeFragment hf;
    private MessageFragment mf;
    private FacultyFragment ff;
    private int NAV_SLIDE_DELAY = 250;

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

        context = this;

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final ActionBar ab = getSupportActionBar();
        if (ab != null) {
            ab.setDisplayHomeAsUpEnabled(true);
            ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        }

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        NavigationView navView = (NavigationView) findViewById(R.id.nav_view);

        navView.getHeaderView(0).findViewById(R.id.imageView3).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (BuildConfig.DEBUG) {

                    final EditText editText = new EditText(context);
                    AlertDialog.Builder alert = new AlertDialog.Builder(context);
                    alert.setView(editText);
                    alert.setPositiveButton("YEAH", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            if (editText.getText().toString().equals("iamareebjamal")) {
                                FirebaseMessaging.getInstance().subscribeToTopic("debug");
                                Toast.makeText(context, "Subscribed to debug mode", Toast.LENGTH_LONG).show();
                            } else {
                                Toast.makeText(context, "WRONG!", Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                    alert.show();
                }

                return true;
            }
        });

        setUpNavView(navView);

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

        if (hf == null)
            hf = new HomeFragment();

        MenuItem home = navView.getMenu().getItem(0);
        home.setChecked(true);
        ft.replace(R.id.rootframe, hf);
        ft.commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                return true;
            default:
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (isNavDrawerOpen()) {
            closeNavDrawer();
        } else {
            super.onBackPressed();
        }
    }

    protected boolean isNavDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(GravityCompat.START);
    }

    public void openNavDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.openDrawer(GravityCompat.START);
        }
    }

    public void closeNavDrawer() {
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        }
    }

    private void setUpNavView(final NavigationView navView) {
        navView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {

            @Override
            public boolean onNavigationItemSelected(final MenuItem mItem) {
                int id = mItem.getItemId();
                final FragmentTransaction ft = getSupportFragmentManager().beginTransaction().setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
                switch (id) {
                    case R.id.nav_home:

                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mItem.setChecked(true);
                                if (hf == null) {
                                    hf = new HomeFragment();
                                } else {
                                    closeNavDrawer();
                                }
                                ft.replace(R.id.rootframe, hf);
                                ft.commit();
                            }
                        }, 0);
                        break;
                    case R.id.nav_messages:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mItem.setChecked(true);
                                if (mf == null) {
                                    mf = new MessageFragment();
                                } else {
                                    closeNavDrawer();
                                }
                                ft.replace(R.id.rootframe, mf);
                                ft.commit();
                            }
                        }, 0);
                        break;
                    case R.id.nav_faculty:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mItem.setChecked(true);
                                if (ff == null) {
                                    ff = new FacultyFragment();
                                } else {
                                    closeNavDrawer();
                                }
                                ft.replace(R.id.rootframe, ff);
                                ft.commit();
                            }
                        }, NAV_SLIDE_DELAY);
                        closeNavDrawer();
                        break;
                    case R.id.nav_department:

                        final Intent i = new Intent(getApplicationContext(), DetailActivity.class);
                        mItem.setChecked(true);
                        closeNavDrawer();
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(i);
                            }
                        }, NAV_SLIDE_DELAY);
                        //navView.getMenu().getItem(prevItem).setChecked(true);
                        break;
                    default:
                        closeNavDrawer();
                        break;
                }

                return false;
            }

        });
    }
}


text:
package org.ovirt.engine.ui.webadmin.section.main.view.popup.scheduling;

import org.ovirt.engine.ui.common.CommonApplicationTemplates;
import org.ovirt.engine.ui.common.idhandler.ElementIdHandler;
import org.ovirt.engine.ui.common.idhandler.WithElementId;
import org.ovirt.engine.ui.common.view.popup.AbstractModelBoundPopupView;
import org.ovirt.engine.ui.common.widget.EntityModelWidgetWithInfo;
import org.ovirt.engine.ui.common.widget.dialog.SimpleDialogPanel;
import org.ovirt.engine.ui.common.widget.editor.generic.EntityModelCheckBoxOnlyEditor;
import org.ovirt.engine.ui.common.widget.editor.generic.StringEntityModelTextBoxEditor;
import org.ovirt.engine.ui.common.widget.form.key_value.KeyValueWidget;
import org.ovirt.engine.ui.common.widget.label.EnableableFormLabel;
import org.ovirt.engine.ui.uicommonweb.models.configure.scheduling.affinity_groups.VmsSelectionModel;
import org.ovirt.engine.ui.uicommonweb.models.configure.scheduling.affinity_groups.model.AffinityGroupModel;
import org.ovirt.engine.ui.webadmin.ApplicationConstants;
import org.ovirt.engine.ui.webadmin.gin.AssetProvider;
import org.ovirt.engine.ui.webadmin.section.main.presenter.popup.scheduling.AffinityGroupPopupPresenterWidget;
import com.google.gwt.core.client.GWT;
import com.google.gwt.editor.client.SimpleBeanEditorDriver;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.inject.Inject;

public class AffinityGroupPopupView extends AbstractModelBoundPopupView<AffinityGroupModel> implements AffinityGroupPopupPresenterWidget.ViewDef {
    interface Driver extends SimpleBeanEditorDriver<AffinityGroupModel, AffinityGroupPopupView> {
    }

    private final Driver driver = GWT.create(Driver.class);

    interface ViewUiBinder extends UiBinder<SimpleDialogPanel, AffinityGroupPopupView> {
        ViewUiBinder uiBinder = GWT.create(ViewUiBinder.class);
    }

    interface ViewIdHandler extends ElementIdHandler<AffinityGroupPopupView> {
        ViewIdHandler idHandler = GWT.create(ViewIdHandler.class);
    }

    @UiField
    @Path(value = "name.entity")
    @WithElementId("name")
    StringEntityModelTextBoxEditor nameEditor;

    @UiField
    @Path(value = "description.entity")
    @WithElementId("description")
    StringEntityModelTextBoxEditor descriptionEditor;

    @Path(value = "positive.entity")
    @WithElementId("positive")
    EntityModelCheckBoxOnlyEditor positiveEditor;

    @UiField(provided = true)
    @Ignore
    EntityModelWidgetWithInfo positiveEditorWithInfo;

    @Path(value = "enforcing.entity")
    @WithElementId("enforcing")
    EntityModelCheckBoxOnlyEditor enforcingEditor;

    @UiField(provided = true)
    @Ignore
    EntityModelWidgetWithInfo enforcingEditorWithInfo;

    @UiField(provided = true)
    @Ignore
    protected KeyValueWidget<VmsSelectionModel> addRemoveVmWidget;

    private final static CommonApplicationTemplates templates = AssetProvider.getTemplates();
    private final static ApplicationConstants constants = AssetProvider.getConstants();

    @Inject
    public AffinityGroupPopupView(EventBus eventBus) {
        super(eventBus);
        initCheckBoxEditors();
        initAddRemoveWidget();
        initWidget(ViewUiBinder.uiBinder.createAndBindUi(this));
        ViewIdHandler.idHandler.generateAndSetIds(this);
        localize();
        driver.initialize(this);
    }

    private void initAddRemoveWidget() {
        addRemoveVmWidget = new KeyValueWidget<VmsSelectionModel>("120px"); //$NON-NLS-1$
    }

    private void initCheckBoxEditors() {
        positiveEditor = new EntityModelCheckBoxOnlyEditor();

        EnableableFormLabel posLabel = new EnableableFormLabel();
        posLabel.setText(constants.affinityGroupPolarityLabel());

        positiveEditorWithInfo = new EntityModelWidgetWithInfo(posLabel, positiveEditor);
        positiveEditorWithInfo.setExplanation(templates.italicText(constants.affinityGroupPolarityInfo()));

        enforcingEditor = new EntityModelCheckBoxOnlyEditor();

        EnableableFormLabel enfLabel = new EnableableFormLabel();
        enfLabel.setText(constants.affinityGroupEnforceTypeLabel());

        enforcingEditorWithInfo = new EntityModelWidgetWithInfo(enfLabel, enforcingEditor);
        enforcingEditorWithInfo.setExplanation(templates.italicText(constants.affinityGroupEnforcInfo()));
    }

    private void localize() {
        nameEditor.setLabel(constants.affinityGroupNameLabel());
        descriptionEditor.setLabel(constants.affinityDescriptionLabel());
    }

    public void edit(AffinityGroupModel model) {
        driver.edit(model);
        addRemoveVmWidget.edit(model.getVmsSelectionModel());
    }

    @Override
    public AffinityGroupModel flush() {
        return driver.flush();
    }

}

redpajama_set_name: RedPajamaGithub


text:
pomelo-http-plugin
==================

Wrap express module as pomelo http plugin.

[wiki][]
[wiki]: https://github.com/pipi32167/pomelo-http-plugin/wiki

###How to use pomelo-http-plugin:

###Single server

For example, your http server name is gamehttp.

#####1. Create config/http.json, configure your http server
```js
{
  "development": {
    "gamehttp": {
      "host": "127.0.0.1",
      "port": 3001
    }
  }
}
```
If you want to support https, you should add more keys to config/http.json
```js
{
  "development": {
    "gamehttp": {
      "useSSL": true,
      "keyFile": "config/key.pem",
      "certFile": "config/cert.pem",
      "host": "127.0.0.1",
      "port": 3001
    }
  }
}
```
#####2. Change servers.json, add gamehttp config
```js
"gamehttp": [{
  "id": "gamehttp",
  "port": 3002,
  "host": "127.0.0.1"
}]
```
#####3. Change adminServer.json, add server type config
```js
{
  "type": "gamehttp",
  "token": "agarxhqb98rpajloaxn34ga8xrunpagkjwlaw3ruxnpaagl29w4rxn"
}
```
#####4. Change app.js
```js
var httpPlugin = require('pomelo-http-plugin');
var path = require('path');
app.configure('development', 'gamehttp', function() {
  app.loadConfig('httpConfig', path.join(app.getBase(), 'config/http.json'));
  app.use(httpPlugin, {
    http: app.get('httpConfig')[app.getServerId()]
  });
});
```
#####5. Create app/servers/gamehttp/route/testRoute.js
```js
module.exports = function(app, http) {

  http.get('/test', function(req, res) {
    res.send('test success')
  });
};
```
#####6. Run your app and open url http://127.0.0.1:3001/test

###Server cluster

This example, we configure our http server as a server cluster, just have a little difference with the before example.

#####1. Create config/http.json, configure your http server
```js
{
  "development": {
    "gamehttp": {
      "isCluster": true,
      "host": "127.0.0.1",
      "port": "3001++"
    }
  }
}
```
If you want to support https, you should add more keys to config/http.json
```js
{
  "development": {
    "gamehttp": {
      "useSSL": true,
      "keyFile": "config/key.pem",
      "certFile": "config/cert.pem",
      "isCluster": true,
      "host": "127.0.0.1",
      "port": "3001++"
    }
  }
}
```
#####2. Change servers.json, add gamehttp config
```js
"gamehttp": [{
  "id": "gamehttp",
  "clusterCount": 2,
  "port": "3101++",
  "host": "127.0.0.1"
}]
```
#####3. Change adminServer.json, add server type config
```js
{
  "type": "gamehttp",
  "token": "agarxhqb98rpajloaxn34ga8xrunpagkjwlaw3ruxnpaagl29w4rxn"
}
```
#####4. Change app.js
```js
var httpPlugin = require('pomelo-http-plugin');
var path = require('path');

app.configure('development', 'gamehttp', function() {
  app.loadConfig('httpConfig', path.join(app.getBase(), 'config/http.json'));
  app.use(httpPlugin, {
    http: app.get('httpConfig')[app.getServerType()]
  });
});
```
#####5. Create app/servers/gamehttp/route/testRoute.js
```js
module.exports = function(app, http) {

  http.get('/test', function(req, res) {
    res.send('test success')
  });
};
```
#####6. Run your app and open urls: http://127.0.0.1:3001/test, http://127.0.0.1:3002/test
#####7. Optional, you can use nginx or any other similar program to reverse proxy the http port, just google it!

## License

The MIT License (MIT)

Copyright (c) 2014 pipi32167

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
<component name="libraryTable">
  <library name="Maven: com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.5.4">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/jaxrs/jackson-jaxrs-json-provider/2.5.4/jackson-jaxrs-json-provider-2.5.4.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/jaxrs/jackson-jaxrs-json-provider/2.5.4/jackson-jaxrs-json-provider-2.5.4-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/com/fasterxml/jackson/jaxrs/jackson-jaxrs-json-provider/2.5.4/jackson-jaxrs-json-provider-2.5.4-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package com.marshalchen.common.demoofui.sampleModules;

import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import com.marshalchen.common.uimodule.cardsSwiped.model.CardModel;
import com.marshalchen.common.uimodule.cardsSwiped.view.CardContainer;
import com.marshalchen.common.uimodule.cardsSwiped.view.SimpleCardStackAdapter;
import com.marshalchen.common.demoofui.R;

public class CardsSwipedActivity extends Activity {

    /**
     * This variable is the container that will host our cards
     */
	private CardContainer mCardContainer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.card_swiped_activity);

		mCardContainer = (CardContainer) findViewById(R.id.layoutview);

		Resources r = getResources();

		SimpleCardStackAdapter adapter = new SimpleCardStackAdapter(this);

		adapter.add(new CardModel("Title1", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title2", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));
		adapter.add(new CardModel("Title3", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture3)));
		adapter.add(new CardModel("Title4", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title5", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));
		adapter.add(new CardModel("Title6", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture3)));
		adapter.add(new CardModel("Title1", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title2", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));
		adapter.add(new CardModel("Title3", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture3)));
		adapter.add(new CardModel("Title4", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title5", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));
		adapter.add(new CardModel("Title6", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture3)));
		adapter.add(new CardModel("Title1", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title2", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));
		adapter.add(new CardModel("Title3", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture3)));
		adapter.add(new CardModel("Title4", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title5", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));
		adapter.add(new CardModel("Title6", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture3)));
		adapter.add(new CardModel("Title1", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title2", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));
		adapter.add(new CardModel("Title3", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture3)));
		adapter.add(new CardModel("Title4", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title5", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));
		adapter.add(new CardModel("Title6", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture3)));
		adapter.add(new CardModel("Title1", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title2", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));
		adapter.add(new CardModel("Title3", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture3)));
		adapter.add(new CardModel("Title4", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1)));
		adapter.add(new CardModel("Title5", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture2)));

        CardModel cardModel = new CardModel("Title1", "Description goes here", r.getDrawable(R.drawable.card_swipted_picture1));
        cardModel.setOnClickListener(new CardModel.OnClickListener() {
           @Override
           public void OnClickListener() {
               Log.i("Swipeable Cards","I am pressing the card");
           }
        });

        cardModel.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
            @Override
            public void onLike() {
                Log.i("Swipeable Cards","I like the card");
            }

            @Override
            public void onDislike() {
                Log.i("Swipeable Cards","I dislike the card");
            }
        });

        adapter.add(cardModel);

		mCardContainer.setAdapter(adapter);
	}
}


text:
/* global init, assertFailure, dump, state */
'use strict';

require('../_init');

const should = require('should'),
    _ = require('underscore'),
    Arrow = require('arrow'),
    Collection = require('../../lib/utils/Collection').Collection,
    Client = require('../../lib/utils/Client').Client,
    Query = require('../../lib/utils/Query').Query;

describe('Query', () => {
    let connector = require('../connector.mock'),
        collectionName = 'appc.loki.js/users',
        loki = new Client(connector),
        collection,
        query;

    before((next) => {
        loki.connect(next);
        collection = new Collection(collectionName, loki);
        query = new Query(collection);
    });

    it('should be able to create an object', (next) => {
        should(query.collection).be.ok();
        should(query.collection).be.type('object');
        should(query.collection.name).be.equal('users');
        next();
    });

    it('should be able to create a query', (next) => {
        let _query = { '$eq': { '$loki': 1 } };
        should(query.createQuery(_query)).be.ok();
        let _loki = query.createQuery(_query).$loki;
        should(_loki.$eq).be.equal(_query.$eq.$loki);
        next();
    });

    it('should return count of collections', (next) => {
        should(query.count()).be.equal(0);
        next();
    });
});

describe('Connector query', () => {

    it("should query for objects", (next) => {
        const _model = Arrow.Model.getModel('appc.loki.js/users');
        var options = {
            where: {'$gt' : { Age : 20 } }
        };
        _model.query(options, (err, resp) => {
            should(err).not.be.ok;
            should(resp).be.ok;
            should(resp).be.Array;
            next();
        });
    });

    it("should query for an object", (next) => {
        const _model = Arrow.Model.getModel('appc.loki.js/users');
        var options = {
            where: {'$eq' : { Age : "32" } }
        };
        _model.query(options, (err, resp) => {
            dump(resp);
            should(err).not.be.ok;
            should(resp).be.ok;
            should(resp).be.Array;
            should(resp).have.lengthOf(1);
            next();
        });
    });

    it("should query for none existing object", (next) => {
        const _model = Arrow.Model.getModel('appc.loki.js/users');
        var options = {
            where: {'$gt' : { Age : "80" } }
        };
        _model.query(options, (err, resp) => {
            should(err).not.be.ok;
            should(resp).be.ok;
            should(resp).be.Array;
            should(resp).have.lengthOf(0);
            next();
        });
    });
});


text:
//
//  REDLog.h
//  REDlib
//
//  Created by Tom Seago on 1/24/12.
//  Copyright 2012 Reality Box Labs LLC. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "REDCLog.h"

/************************************************************
 Logging Macros
 ************************************************************/
#ifdef __cplusplus
extern "C" {
#endif

extern const int RLEVEL_TRACE;
extern const int RLEVEL_DEBUG;
extern const int RLEVEL_INFO;
extern const int RLEVEL_WARNING;
extern const int RLEVEL_WARN;
extern const int RLEVEL_ERROR;
extern const int RLEVEL_ERR;
extern const int RLEVEL_CRITICAL;
extern const int RLEVEL_CRIT;

extern const int RLEVEL_DEFAULT;

extern void RLog(NSString *format, ...);
extern void RLogLineNo(const char* file, int lineno, int level, NSString* facility, NSString* format, ...);
extern void RLogv(int level, NSString* facility, NSString* format, va_list args);
extern void RLogLineNov(const char* file, int lineno, int level, NSString* facility, NSString* format, va_list args);

extern void RLogEnable(NSString* sinkName);

#ifdef __cplusplus
}
#endif

// Undefine everything first just in case both this file and REDCLog.h get included
#undef RLOG
#undef RLOG_TRACE
#undef RLOG_DEBUG
#undef RLOG_INFO
#undef RLOG_WARNING
#undef RLOG_WARN
#undef RLOG_ERROR
#undef RLOG_ERR
#undef RLOG_CRITICAL
#undef RLOG_CRIT

#define RLOG(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_DEFAULT, facility, __VA_ARGS__)

#define RLOG_TRACE(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_TRACE, facility, __VA_ARGS__)
#define RLOG_DEBUG(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_DEBUG, facility, __VA_ARGS__)
#define RLOG_INFO(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_INFO, facility, __VA_ARGS__)
#define RLOG_WARNING(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_WARNING, facility, __VA_ARGS__)
#define RLOG_WARN(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_WARN, facility, __VA_ARGS__)
#define RLOG_ERROR(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_ERROR, facility, __VA_ARGS__)
#define RLOG_ERR(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_ERR, facility, __VA_ARGS__)
#define RLOG_CRITICAL(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_CRITICAL, facility, __VA_ARGS__)
#define RLOG_CRIT(facility, ...) RLogLineNo(__FILE__,__LINE__, RLEVEL_CRIT, facility, __VA_ARGS__)

/************************************************************
    REDLog Class
 ************************************************************/

@protocol REDLogSink;

@interface REDLog : NSObject
{
    NSString* _adid;
    NSMutableArray* _registrations;

    BOOL _toNSLog;
    NSDateFormatter* _nslogDateFormatter;
}

@property (nonatomic, retain) NSString* adid;

+(REDLog*) sharedInstance;

+(NSString*) macaddress;
+(NSString*) stringFromMD5:(NSString*)src;
+(NSString*) makeADID;
+(NSString*) makeGDID;

+(NSString*) stringForLevel:(int)level;
+(NSString*) stringForLevelFixedWidth:(int)level;

-(void) registerSink:(id<REDLogSink>)sink forEverything:(BOOL)forAll;
-(void) unregisterSink:(id<REDLogSink>)sink;

-(NSArray*) allSinks;

-(void) setLevel:(int)level forSink:(id<REDLogSink>)sink;
-(void) addFacility:(NSString*)facility forSink:(id<REDLogSink>)sink;
-(void) removeFacility:(NSString*)facility forSink:(id<REDLogSink>)sink;

-(void) log:(NSString*)msg level:(int)level facility:(NSString*)facility data:(NSDictionary*)data;

-(void) addNSLog;
-(void) removeNSLog;

-(id<REDLogSink>) addNetworkKey:(NSString*)key;
-(id<REDLogSink>) addNetworkKey:(NSString*)key forURL:(NSString*)url;

@end


text:
angular
  .module('mage')
  .controller('AdminTeamsController', AdminTeamsController);

AdminTeamsController.$inject = ['$scope', '$uibModal', '$filter', '$location', 'Team'];

function AdminTeamsController($scope, $uibModal, $filter, $location, Team) {
  $scope.teams = [];
  $scope.page = 0;
  $scope.itemsPerPage = 10;

  Team.query(function(teams) {
    $scope.teams = _.reject(teams, function(team) { return team.teamEventId; });
  });

  $scope.filterTeams = function(team) {
    var filteredTeams = $filter('filter')([team], $scope.teamSearch);
    return filteredTeams && filteredTeams.length;
  };

  $scope.reset = function() {
    $scope.page = 0;
    $scope.teamSearch = '';
  };

  $scope.newTeam = function() {
    $location.path('/admin/teams/new');
  };

  $scope.gotoTeam = function(team) {
    $location.path('/admin/teams/' + team.id);
  };

  $scope.editTeam = function($event, team) {
    $event.stopPropagation();

    $location.path('/admin/teams/' + team.id + '/edit');
  };

  $scope.deleteTeam = function($event, team) {
    $event.stopPropagation();

    var modalInstance = $uibModal.open({
      templateUrl: '/app/admin/teams/team-delete.html',
      resolve: {
        team: function () {
          return team;
        }
      },
      controller: ['$scope', '$uibModalInstance', 'team', function ($scope, $uibModalInstance, team) {
        $scope.team = team;

        $scope.deleteTeam = function(team) {
          team.$delete(function() {
            $uibModalInstance.close(team);
          });
        };

        $scope.cancel = function () {
          $uibModalInstance.dismiss('cancel');
        };
      }]
    });

    modalInstance.result.then(function (team) {
      $scope.teams = _.reject($scope.teams, function(t) { return t.id === team.id; });
    });
  };
}


text:
using System.Collections.Generic;
using iPhone.Applications.Phone.Model;

namespace iPhone.Applications.Phone.Repositories
{
    public interface IContactRepository
    {
        IEnumerable<Group> GetGroups();
        IEnumerable<Contact> GetContacts(Group group);
    }
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;

namespace DevCamp.WebApp.Utils
{
    public class Settings
    {
        //####    HOL 2    ######
        public static string INCIDENT_API_URL = ConfigurationManager.AppSettings["INCIDENT_API_URL"];
        public static string AZURE_STORAGE_ACCOUNT = ConfigurationManager.AppSettings["AZURE_STORAGE_ACCOUNT"];
        public static string AZURE_STORAGE_KEY = ConfigurationManager.AppSettings["AZURE_STORAGE_ACCESS_KEY"];
        public static string AZURE_STORAGE_BLOB_CONTAINER = ConfigurationManager.AppSettings["AZURE_STORAGE_BLOB_CONTAINER"];
        public static string AZURE_STORAGE_QUEUE = ConfigurationManager.AppSettings["AZURE_STORAGE_QUEUE"];
        public static string AZURE_STORAGE_CONNECTIONSTRING = String.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", AZURE_STORAGE_ACCOUNT, AZURE_STORAGE_KEY);
        public static string REDISCCACHE_KEY_INCIDENTDATA = "incidentdata";

        public static string REDISCACHE_HOSTNAME = ConfigurationManager.AppSettings["REDISCACHE_HOSTNAME"];
        public static string REDISCACHE_PORT = ConfigurationManager.AppSettings["REDISCACHE_PORT"];
        public static string REDISCACHE_SSLPORT = ConfigurationManager.AppSettings["REDISCACHE_SSLPORT"];
        public static string REDISCACHE_PRIMARY_KEY = ConfigurationManager.AppSettings["REDISCACHE_PRIMARY_KEY"];
        public static string REDISCACHE_CONNECTIONSTRING = $"{REDISCACHE_HOSTNAME}:{REDISCACHE_SSLPORT},password={REDISCACHE_PRIMARY_KEY},abortConnect=false,ssl=true";
        //####    HOL 2   ######
        //####    HOL 3    ######
        public static string AAD_APP_ID = ConfigurationManager.AppSettings["AAD_APP_ID"];
        public static string AAD_INSTANCE = ConfigurationManager.AppSettings["AAD_INSTANCE"];
        public static string AAD_APP_REDIRECTURI = ConfigurationManager.AppSettings["AAD_APP_REDIRECTURI"];
        public static string AAD_TENANTID_CLAIMTYPE = "http://schemas.microsoft.com/identity/claims/tenantid";
        public static string AAD_OBJECTID_CLAIMTYPE = "http://schemas.microsoft.com/identity/claims/objectidentifier";
        public static string AAD_AUTHORITY = ConfigurationManager.AppSettings["AAD_AUTHORITY"];
        public static string AAD_LOGOUT_AUTHORITY = ConfigurationManager.AppSettings["AAD_LOGOUT_AUTHORITY"];
        public static string GRAPH_API_URL = ConfigurationManager.AppSettings["GRAPH_API_URL"];
        public static string AAD_APP_SECRET = ConfigurationManager.AppSettings["AAD_APP_SECRET"];
        public static string AAD_GRAPH_SCOPES = ConfigurationManager.AppSettings["AAD_GRAPH_SCOPES"];
        public static string GRAPH_CURRENT_USER_URL = GRAPH_API_URL + "/v1.0/me";
		public static string GRAPH_SENDMESSAGE_URL = GRAPH_CURRENT_USER_URL + "/sendMail";
		public static string GRAPH_CONTACTS_URL = GRAPH_CURRENT_USER_URL + "/contacts";
		public static string GRAPH_EVENTS_URL = GRAPH_CURRENT_USER_URL + "/events";
        public static string SESSIONKEY_ACCESSTOKEN = "accesstoken";
        public static string SESSIONKEY_USERINFO = "userinfo";

        public static string EMAIL_MESSAGE_BODY = getEmailMessageBody();
        public static string EMAIL_MESSAGE_SUBJECT = "New Incident Reported";
        public static string EMAIL_MESSAGE_TYPE = "HTML";
        //####    HOL 3    ######

        static string getEmailMessageBody()
        {
            StringBuilder emailContent = new StringBuilder();
            emailContent.Append(@"<meta http-equiv='Content-Type' content='text/html; charset=us-ascii\'>");
            emailContent.Append(@"<title></title>");
            emailContent.Append(@"");
            emailContent.Append(@" ");
            emailContent.Append(@"
 ");
            emailContent.Append(@"
City Power & Light
 ");
            emailContent.Append(@"
New Incident was reported by {0} {1}
 ");
            emailContent.Append(@"
A new incident has been reported to the City Power & Light outage system.
 ");
            emailContent.Append(@"
 ");
            emailContent.Append(@"
 ");
            emailContent.Append(@" ");
            emailContent.Append(@"");
            return emailContent.ToString();
        }
    }
}


text:
<?php

namespace Model;

use cryptopupua\KunaApi\Model\Me;
use cryptopupua\KunaApi\Model\MyAccount;
use PHPUnit\Framework\TestCase;

/**
 * Class MeTest
 * @package Model
 */
class MeTest extends TestCase
{
    public function testModel()
    {
        $account1 = new MyAccount();
        $account1->setBalance(1000.1);
        $account1->setCurrency('btc');
        $account1->setLocked(150.8);

        static::assertEquals(1000.1, $account1->getBalance());
        static::assertEquals('btc', $account1->getCurrency());
        static::assertEquals(150.8, $account1->getLocked());

        $account2 = new MyAccount();

        $model = new Me();
        $model->setEmail('email');
        $model->setActivated(false);
        $model->setAccounts([$account1, $account2]);

        static::assertEquals('email', $model->getEmail());
        static::assertFalse($model->isActivated());
        static::assertCount(2, $model->getAccounts());
    }
}


text: google-site-verification: google0a0a07483f5a0553.html


text:
using BillyService.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Billy.Models
{

    public class Root
    {
        public object contact { get; set; }
    }
}


text:
**PRESENZA**: respiro, pensiero, voce, mani
**HARDWARE**: lapis, carta, laptop
**SOFTWARE**: browser/google, google fogli, markdown, git/github, processing

### Software (_essenziali e {consigliati}_)

##### PER PARTECIPARE
- github, {, github uploader, git, sourcetree}
- markdown {, hackpad}

##### PER PROGETTARE
- data: google fogli, openrefine, raw, plot.ly, xml, JSON
- code: processing, {js, p5js, d3, html5, css}
- altri: {sublimetext, cyberduck, chrome, firefox, strumenti sviluppatori, ...}
- phys: {arduino, ar, wood, plastic, liquids, servo, leds...}

##### PER DOCUMENTARE
- markdown su github
- processing to img/pdf/video
- {d3 to svg tools}
- camera / video
- indesign

### Letture critiche

1.  **_cosa è_**
2.  **_cosa potrebbe significare_**
3.  **_come funziona_**


text:
<?php
namespace Lm\Console\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Lm\Console\Helpers\CurlHelper;
use Lm\Console\Helpers\PropelAtomFeed;

class PropelCommitImportCommand extends Command
{
	protected function configure()
	{
		$this
            ->setName('propelcommit:import_to_db')
            ->setDescription('Import the master.atom commit entries to database')
            ->addArgument(
                'date',
                InputArgument::OPTIONAL,
                'Which entries you wnat to import?'
            )
        ;

	}

	protected function execute(InputInterface $input, OutputInterface $output)
	{
		$date = $input->getArgument('date');
		//we don't anything right now with this parameter

		//check if master.atom.txt' exists
		$filename = __DIR__ .'\\master.atom.txt';
		$file = fopen( $filename, 'r');

		if($file){
			fclose($file);

			//process the atom feed
			$this->processAtomCommit($filename);

			$output->writeln('Done!\n');
		}else {
			$output->writeln('File ' . __DIR__ .'\\master.atom.txt was not found' );
		}

	}

	/**
	* Process the xml master.atom fetched from github repo
	*
	* @param string fileaname
	**/
	private function processAtomCommit($filename)
	{
		$propelcommit = new PropelAtomFeed($filename);

		$propelcommit->saveNewCommits();

	}
}

?>


text:
#ifndef QPRINTPREVIEWDIALOG_H
#define QPRINTPREVIEWDIALOG_H

#include <QtGui/qdialog.h>

#ifndef QT_NO_PRINTPREVIEWDIALOG

QT_BEGIN_HEADER

QT_BEGIN_NAMESPACE

QT_MODULE(Gui)

class QGraphicsView;
class QPrintPreviewDialogPrivate;

class Q_GUI_EXPORT QPrintPreviewDialog : public QDialog
{
    Q_OBJECT
    Q_DECLARE_PRIVATE(QPrintPreviewDialog)

public:
    explicit QPrintPreviewDialog(QWidget *parent = 0, Qt::WindowFlags flags = 0);
    explicit QPrintPreviewDialog(QPrinter *printer, QWidget *parent = 0, Qt::WindowFlags flags = 0);
    ~QPrintPreviewDialog();

#ifdef Q_NO_USING_KEYWORD
#ifndef Q_QDOC
    void open() { QDialog::open(); }
#endif
#else
    using QDialog::open;
#endif
    void open(QObject *receiver, const char *member);

    QPrinter *printer();

    void setVisible(bool visible);
    void done(int result);

Q_SIGNALS:
    void paintRequested(QPrinter *printer);

private:
    Q_PRIVATE_SLOT(d_func(), void _q_fit(QAction *action))
    Q_PRIVATE_SLOT(d_func(), void _q_zoomIn())
    Q_PRIVATE_SLOT(d_func(), void _q_zoomOut())
    Q_PRIVATE_SLOT(d_func(), void _q_navigate(QAction *action))
    Q_PRIVATE_SLOT(d_func(), void _q_setMode(QAction *action))
    Q_PRIVATE_SLOT(d_func(), void _q_pageNumEdited())
    Q_PRIVATE_SLOT(d_func(), void _q_print())
    Q_PRIVATE_SLOT(d_func(), void _q_pageSetup())
    Q_PRIVATE_SLOT(d_func(), void _q_previewChanged())
    Q_PRIVATE_SLOT(d_func(), void _q_zoomFactorChanged())

    void *dummy; // ### Qt 5 - remove me
};

QT_END_NAMESPACE

QT_END_HEADER

#endif // QT_NO_PRINTPREVIEWDIALOG

#endif // QPRINTPREVIEWDIALOG_H


text:
import React, { Component } from 'react'
import { styled } from '@material-ui/core/styles'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Link, withRouter } from 'react-router-dom'
import includes from 'lodash/fp/includes'
import sortBy from 'lodash/fp/sortBy'
import toLower from 'lodash/fp/toLower'

import { lighten } from '@mui/material/styles'
import Button from '@mui/material/Button'
import Grid from '@mui/material/Grid'
import Hidden from '@mui/material/Hidden'
import Table from '@mui/material/Table'
import TableBody from '@mui/material/TableBody'
import TableCell from '@mui/material/TableCell'
import TableHead from '@mui/material/TableHead'
import TableRow from '@mui/material/TableRow'
import Typography from '@mui/material/Typography'

import * as actions from '../redux/actions'
import ContentLimiter from './ContentLimiter'
import Hero from './Hero'
import SearchBox from './SearchBox'

const PREFIX = 'SongList'

const classes = {
	highlight: `${PREFIX}-highlight`,
	tableRow: `${PREFIX}-tableRow`,
}

const Root = styled('div')(({ theme }) => ({
	[`& .${classes.highlight}`]:
		theme.palette.mode === 'light'
			? {
					color: theme.palette.secondary.main,
					backgroundColor: lighten(
						theme.palette.secondary.light,
						0.85
					),
			  }
			: {
					color: theme.palette.text.primary,
					backgroundColor: theme.palette.secondary.dark,
			  },

	[`& .${classes.tableRow}`]: {
		cursor: 'pointer',
	},
}))

class SongList extends Component {
	static propTypes = {
		classes: PropTypes.object,
		songs: PropTypes.array,
	}
	state = {
		searchText: '',
	}

	addToSet = song => {
		window.alert('TODO: move to redux')
		/*db.get(this.props.setId)
			.then(doc => {
				const data = Object.assign({}, doc);

				data.songs = data.songs || [];
				data.songs.push({
					_id: song._id,
					key: song.key
				});
				data.songs = uniqBy(data.songs, '_id');

				db.put(data)
					.then(() => {
						if (this.props.history) {
							const location = {
								pathname: `/sets/${doc._id}`
							};

							this.props.history.push(location);
						}
					})
					.catch(err => {
						if (err.name === 'conflict') {
							console.error('SongList.addToSet: conflict -', err);
						} else {
							console.error('SongList.addToSet -', err);
						}
					});
			})
			.catch(err => {
				console.error(err);
			});*/
	}

	filterSongs = song => {
		const contains = includes(toLower(this.state.searchText))
		return (
			contains(toLower(song.title)) ||
			contains(toLower(song.content)) ||
			contains(toLower(song.author))
		)
	}

	handleSearch = searchText => this.setState({ searchText })

	handleTableRowClick = songId => () =>
		this.props.history.push(`/songs/${songId}`)

	render() {
		const { songs } = this.props

		const filteredSongs = songs.filter(this.filterSongs)
		const sortedSongs = sortBy('title')(filteredSongs)
		//const isAddToSet = /\/add-to-set\//.test( path );
		const isAddToSet = /\/add-to-set\//.test(window.location.href)

		return (
			<Root>
				<Hero>
					<ContentLimiter>
						<Grid
							container
							alignItems={'center'}
							justifyContent={'space-between'}
						>
							<Grid item>
								<Typography
									variant={'h4'}
									sx={{ fontWeight: 600 }} //TODO: move this into the global theme
								>
									Songs
								</Typography>
							</Grid>

							<Grid item>
								<Grid
									container
									alignItems={'center'}
									spacing={2}
								>
									<Grid item>
										<SearchBox
											onSearch={this.handleSearch}
											placeholder={
												'Titles, words, authors'
											}
										/>
									</Grid>

									<Grid item>
										<Button
											to={'/songs/new'}
											component={Link}
											color={'primary'}
											variant={'contained'}
										>
											New song
										</Button>
									</Grid>
								</Grid>
							</Grid>
						</Grid>
					</ContentLimiter>
				</Hero>
				<Table>
					<TableHead>
						<TableRow>
							<TableCell>Song</TableCell>
							<Hidden only={'xs'}>
								<TableCell>Author</TableCell>
							</Hidden>
							{isAddToSet && <TableCell>Action</TableCell>}
						</TableRow>
					</TableHead>

					<TableBody>
						{sortedSongs.map(song => (
							<TableRow
								className={classes.tableRow}
								onClick={this.handleTableRowClick(song.id)}
								hover
								key={song.id}
							>
								<TableCell>
									<Typography gutterBottom variant={'h6'}>
										{song.title}
									</Typography>
								</TableCell>

								<Hidden only={'xs'}>
									<TableCell>{song.author}</TableCell>
								</Hidden>

								{isAddToSet && (
									<TableCell>
										<Button
											onClick={() => this.addToSet(song)}
											variant={'outlined'}
										>
											Add
										</Button>
									</TableCell>
								)}
							</TableRow>
						))}
					</TableBody>
				</Table>
			</Root>
		)
	}
}

export default connect(null, actions)(withRouter(SongList))


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

	<title>Processing.js test of textAlign()</title>

textAlign() align tests

	<canvas id="display"></canvas>


text:
(function trackingHashRemover(window, undefined) {
  'use strict';
  var trackPattern = /^#?\.[a-zA-Z0-9]{8,}/, interval;
  function removeHash(hsh) {
    var subst, idx;
    if (typeof hsh === 'symbol') hsh = '';
    hsh += '';
    idx = hsh.indexOf('#');
    if (idx !== -1) {
      subst = hsh.slice(idx);
      if (trackPattern.test(subst)) return hsh.slice(0, idx);
      else return hsh;
    } else return '';
  }
  function locHashRemover() {
    var hsh = location.hash;
    if (trackPattern.test(hsh)) location.hash = '';
    else {
      clearInterval(interval);
      interval = null;
    }
  }
  function removeHashes() {
    var links = document.getElementsByTagName('a'),
      forms = document.getElementsByTagName('form'), i;
    interval = interval || setInterval(locHashRemover, 16);
    for (i in links)
      if (links.hasOwnProperty(i))
        i.hash = removeHash(i.hash);
    for (i in forms)
      if(forms.hasOwnProperty(i))
        i.action = removeHash(i.action);
  }
  function dclRemover() {
    document.removeEventListener('DOMContentLoaded', dclRemover, false);
    removeHashes();
  }
  function loadRemover() {
    window.removeEventListener('load', loadRemover, false);
    removeHashes();
  }
  removeHashes();
  document.addEventListener('readystatechange', removeHashes, false);
  document.addEventListener('DOMContentLoaded', dclRemover, false);
  window.addEventListener('load', loadRemover, false);
  window.addEventListener('hashchange', removeHashes, false);
}(window));


text:
@implementation XLFormOptionsObject
{
    NSString * _formDisplaytext;
    id _formValue;
}

@synthesize tag;

+(XLFormOptionsObject *)formOptionsObjectWithValue:(id)value displayText:(NSString *)displayText
{
    return [[XLFormOptionsObject alloc] initWithValue:value displayText:displayText];
}

-(id)initWithValue:(id)value displayText:(NSString *)displayText
{
    self = [super init];
    if (self){
        _formValue = value;
        _formDisplaytext = displayText;
        tag = @"";
    }
    return self;
}

+(XLFormOptionsObject *)formOptionsOptionForValue:(id)value fromOptions:(NSArray *)options
{
    for (XLFormOptionsObject * option in options) {
        if ([option.formValue isEqual:value]){
            return option;
        }
    }
    return nil;
}

+(XLFormOptionsObject *)formOptionsOptionForDisplayText:(NSString *)displayText fromOptions:(NSArray *)options
{
    for (XLFormOptionsObject * option in options) {
        if ([option.formDisplayText isEqualToString:displayText]){
            return option;
        }
    }
    return nil;
}

-(BOOL)isEqual:(id)object
{
    if (![[self class] isEqual:[object class]]){
        return NO;
    }
    return [self.formValue isEqual:((XLFormOptionsObject *)object).formValue];
}

#pragma mark - XLFormOptionObject

-(NSString *)formDisplayText
{
    return _formDisplaytext;
}

-(id)formValue
{
    return _formValue;
}

@end


text:
package org.apache.spark.streaming.util

import java.io._
import java.net.URI
import java.nio.ByteBuffer

import scala.util.Try

import org.apache.hadoop.conf.Configuration
import org.apache.hadoop.fs.{FSDataOutputStream, FileSystem}

/**
 * A writer for writing byte-buffers to a write ahead log file.
 */
private[streaming] class WriteAheadLogWriter(path: String, hadoopConf: Configuration)
  extends Closeable {

  private lazy val stream = HdfsUtils.getOutputStream(path, hadoopConf)

  private lazy val hadoopFlushMethod = {
    // Use reflection to get the right flush operation
    val cls = classOf[FSDataOutputStream]
    Try(cls.getMethod("hflush")).orElse(Try(cls.getMethod("sync"))).toOption
  }

  private var nextOffset = stream.getPos()
  private var closed = false

  /** Write the bytebuffer to the log file */
  def write(data: ByteBuffer): WriteAheadLogFileSegment = synchronized {
    assertOpen()
    data.rewind() // Rewind to ensure all data in the buffer is retrieved
    val lengthToWrite = data.remaining()
    val segment = new WriteAheadLogFileSegment(path, nextOffset, lengthToWrite)
    stream.writeInt(lengthToWrite)
    if (data.hasArray) {
      stream.write(data.array())
    } else {
      // If the buffer is not backed by an array, we transfer using temp array
      // Note that despite the extra array copy, this should be faster than byte-by-byte copy
      while (data.hasRemaining) {
        val array = new Array[Byte](data.remaining)
        data.get(array)
        stream.write(array)
      }
    }
    flush()
    nextOffset = stream.getPos()
    segment
  }

  override def close(): Unit = synchronized {
    closed = true
    stream.close()
  }

  private def flush() {
    hadoopFlushMethod.foreach { _.invoke(stream) }
    // Useful for local file system where hflush/sync does not work (HADOOP-7844)
    stream.getWrappedStream.flush()
  }

  private def assertOpen() {
    HdfsUtils.checkState(!closed, "Stream is closed. Create a new Writer to write to file.")
  }
}


text:
const _ = require('lodash');
const bluebird = require('bluebird');
const Schema = require('mongoose').Schema;

const bcrypt = bluebird.promisifyAll(require('bcryptjs'));

const name = 'User';
const schema = new Schema({
  username: { type: String, required: true, index: { unique: true } },
  password: { type: String, required: true },
}, {
  toObject: {
    transform: (doc, ret) => {
      /* eslint-disable no-param-reassign */
      delete ret.__v;
      delete ret._id;
      /* eslint-enable no-param-reassign */
    },
  },
});

schema.pre('save', function (next) {
  const user = this;
  if (user.isModified('password') || user.isNew) {
    bcrypt.genSaltAsync(10)
      .then(salt => bcrypt.hashAsync(user.password, salt))
      .then(hash => {
        user.password = hash;
        next();
      })
      .catch(next);
  } else {
    next();
  }
});

schema.methods.comparePassword = function (password) {
  const user = this;
  return bcrypt.compareAsync(password, user.password);
};

module.exports = (connection) =>
  _.includes(connection.modelNames(), name)
    ? connection.model(name)
    : connection.model(name, schema);


text:
using System;
using System.Collections.Generic;
using XenAdmin.Network;
using XenAPI;
using XenAdmin.Core;
using System.Xml;

namespace XenAdmin.Actions.VMActions
{
    public enum InstallMethod
    {
        None,
        CD,
        Network
    }

    public enum BootMode { BIOS_BOOT, UEFI_BOOT, UEFI_SECURE_BOOT, NOT_AVAILABLE }

    public static class EnumExt
    {
        public static string StringOf(this BootMode x)
        {
            switch (x)
            {
                case BootMode.BIOS_BOOT:
                    return Messages.BIOS_BOOT;
                case BootMode.UEFI_BOOT:
                    return Messages.UEFI_BOOT;
                case BootMode.UEFI_SECURE_BOOT:
                    return Messages.UEFI_SECURE_BOOT;
                default:
                    return Messages.UNAVAILABLE;
            }
        }
    }

    public class CreateVMAction : AsyncAction
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private readonly string NameLabel;
        private readonly string NameDescription;
        private readonly InstallMethod InsMethod;
        private readonly string PvArgs;
        private readonly VDI Cd;
        private readonly string Url;
        private readonly BootMode BootMode;
        private readonly Host HomeServer;
        private readonly long VcpusMax;
        private readonly long VcpusAtStartup;
        private readonly long MemoryDynamicMin, MemoryDynamicMax, MemoryStaticMax;
        private readonly List<DiskDescription> Disks;
        private readonly List<VIF> Vifs;
        private readonly bool StartAfter;
        private readonly Host CopyBiosStringsFrom;
        private readonly SR FullCopySR;
        private readonly List<VGPU> vGpus;
        private readonly long CoresPerSocket;
        private readonly string cloudConfigDriveTemplateText;
        private SR firstSR = null;

        private Action<VMStartAbstractAction, Failure> _startDiagnosisForm;
        private Action<VM, bool> _warningDialogHAInvalidConfig;

        private bool PointOfNoReturn;

        private bool assignOrRemoveVgpu;

        /// <summary>
        /// These are the RBAC dependencies that you always need to create a VM. Check CreateVMAction constructor for runtime dependent dependencies.
        /// </summary>
        public static RbacMethodList StaticRBACDependencies = new RbacMethodList(
            // provision VM
            "vm.provision",
            "vm.set_other_config",
            // set VM Params
            "vm.set_name_label",
            "vm.set_name_description",
            "vm.set_VCPUs_max",
            "vm.set_VCPUs_at_startup",
            // set VM Boot Params
            "vm.set_HVM_boot_params",
            "vm.set_PV_args",
            "vm.set_other_config",
            // Add CD Drive
            "vbd.eject",
            "vbd.insert",
            // Create CD Drive
            "vbd.create",
            // Add disks
            "vdi.destroy",
            "vdi.create",
            "vdi.set_sm_config",
            "vbd.create",
            "vbd.destroy",
            "vdi.copy",
            // Add networks
            "vif.create",
            "vm.set_platform"
        );

        public CreateVMAction(IXenConnection connection, VM template, Host copyBiosStringsFrom,
            string name, string description, InstallMethod installMethod,
            string pvArgs, VDI cd, string url, BootMode bootMode, Host homeServer, long vcpusMax, long vcpusAtStartup,
            long memoryDynamicMin, long memoryDynamicMax, long memoryStaticMax,
            List<DiskDescription> disks, SR fullCopySR, List<VIF> vifs, bool startAfter,
            Action<VM, bool> warningDialogHAInvalidConfig,
            Action<VMStartAbstractAction, Failure> startDiagnosisForm,
            List<VGPU> vGpus, bool modifyVgpuSettings, long coresPerSocket, string cloudConfigDriveTemplateText)
            : base(connection, string.Format(Messages.CREATE_VM, name),
            string.Format(Messages.CREATE_VM_FROM_TEMPLATE, name, Helpers.GetName(template)))
        {
            Template = template;
            CopyBiosStringsFrom = copyBiosStringsFrom;
            FullCopySR = fullCopySR;
            NameLabel = name;
            NameDescription = description;
            InsMethod = installMethod;
            PvArgs = pvArgs;
            Cd = cd;
            Url = url;
            BootMode = bootMode;
            HomeServer = homeServer;
            VcpusMax = vcpusMax;
            VcpusAtStartup = vcpusAtStartup;
            MemoryDynamicMin = memoryDynamicMin;
            MemoryDynamicMax = memoryDynamicMax;
            MemoryStaticMax = memoryStaticMax;
            Disks = disks;
            Vifs = vifs;
            StartAfter = startAfter;
            _warningDialogHAInvalidConfig = warningDialogHAInvalidConfig;
            _startDiagnosisForm = startDiagnosisForm;
            this.vGpus = vGpus;
            CoresPerSocket = coresPerSocket;
            this.cloudConfigDriveTemplateText = cloudConfigDriveTemplateText;

            Pool pool_of_one = Helpers.GetPoolOfOne(Connection);
            if (HomeServer != null || pool_of_one != null) // otherwise we have no where to put the action
                AppliesTo.Add(HomeServer != null ? HomeServer.opaque_ref : pool_of_one.opaque_ref);

            assignOrRemoveVgpu = vGpus != null && vGpus.Count > 0 || modifyVgpuSettings && Helpers.GpuCapability(Connection);

            #region RBAC Dependencies

            if (StartAfter)
                ApiMethodsToRoleCheck.Add("vm.start");
            if (HomeServerChanged())
                ApiMethodsToRoleCheck.Add("vm.set_affinity");
            if (Template.memory_dynamic_min != MemoryDynamicMin || Template.memory_dynamic_max != MemoryDynamicMax || Template.memory_static_max != MemoryStaticMax)
                ApiMethodsToRoleCheck.Add("vm.set_memory_limits");

            if (assignOrRemoveVgpu)
            {
                ApiMethodsToRoleCheck.Add("VGPU.destroy");
                ApiMethodsToRoleCheck.Add("VGPU.create");
            }

            ApiMethodsToRoleCheck.AddRange(StaticRBACDependencies);

            ApiMethodsToRoleCheck.AddRange(Role.CommonTaskApiList);
            ApiMethodsToRoleCheck.AddRange(Role.CommonSessionApiList);

            #endregion
        }

        protected override void Run()
        {
            if (FullCopySR != null)
            {
                Description = string.Format(Messages.COPYING_TEMPLATE, Helpers.GetName(Template), FullCopySR.Name());
                RelatedTask = VM.async_copy(Session, Template.opaque_ref, Helpers.MakeHiddenName(NameLabel), FullCopySR.opaque_ref);
            }
            else
            {
                Description = string.Format(Messages.CLONING_TEMPLATE, Helpers.GetName(Template));
                RelatedTask = VM.async_clone(Session, Template.opaque_ref, Helpers.MakeHiddenName(NameLabel));
            }

            PollToCompletion(0, 10);

            VM = Connection.WaitForCache(new XenRef<VM>(Result));

            ApplyRecommendationsForVendorDevice();
            CopyBiosStrings();
            SetXenCenterProperties();
            ProvisionVM();
            SetVMParams();
            SetVMBootParams();
            AddCdDrive();
            AddDisks();
            AddNetworks();
            XenAdminConfigManager.Provider.ShowObject(VM.opaque_ref);
            VM.IsBeingCreated = false;
            PointOfNoReturn = true;

            if (Helpers.ContainerCapability(Connection))
                CloudCreateConfigDrive();

            AssignVgpu();

            if (StartAfter)
            {
                Description = Messages.STARTING_VM;
                var startAction = new VMStartAction(VM, _warningDialogHAInvalidConfig, _startDiagnosisForm);
                startAction.RunAsync();
            }

            Description = Messages.VM_SUCCESSFULLY_CREATED;
        }

        private void ApplyRecommendationsForVendorDevice()
        {
            var pool = Helpers.GetPoolOfOne(Connection);
            bool poolPolicyNoVendorDevice = pool == null || pool.policy_no_vendor_device;
            bool hasVendorDeviceRecommendation = Template.HasVendorDeviceRecommendation();

            if (hasVendorDeviceRecommendation && !poolPolicyNoVendorDevice && !Helpers.FeatureForbidden(VM, Host.RestrictVendorDevice))
            {
                log.DebugFormat("Recommendation (has-vendor-device = true) has been found on the template ({0}) and the host is licensed, so applying it on VM ({1}) being created.", Template.opaque_ref, VM.opaque_ref);
                VM.set_has_vendor_device(Connection.Session, VM.opaque_ref, true);
            }
            else
            {
                log.DebugFormat("Recommendation (has-vendor-device = true) has not been applied on the VM ({0}) being created.", VM.opaque_ref);

                if (!hasVendorDeviceRecommendation)
                    log.DebugFormat("Recommendation (has-vendor-device) is not set or false on the template ({0}).", Template.opaque_ref);

                if (poolPolicyNoVendorDevice)
                    log.DebugFormat("pool.policy_no_vendor_device returned {0}", poolPolicyNoVendorDevice);

                if (Helpers.FeatureForbidden(VM, Host.RestrictVendorDevice))
                    log.DebugFormat("Helpers.FeatureForbidden(VM, Host.RestrictVendorDevice) returned {0}", Helpers.FeatureForbidden(VM, Host.RestrictVendorDevice));
            }
        }

        private void CloudCreateConfigDrive()
        {
            if (Template.CanHaveCloudConfigDrive() && !string.IsNullOrEmpty(cloudConfigDriveTemplateText))
            {
                Description = Messages.CREATING_CLOUD_CONFIG_DRIVE;

                var parameters = new Dictionary<string, string>();
                parameters.Add("vmuuid", VM.uuid);
                parameters.Add("sruuid", firstSR.uuid);
                parameters.Add("configuration", cloudConfigDriveTemplateText.Replace("\r\n", "\n"));

                var action = new RunPluginAction(Connection, HomeServer ?? Helpers.GetCoordinator(Connection),
                            "xscontainer",//plugin
                            "create_config_drive",//function
                            parameters,
                            true); //hidefromlogs

                action.RunSync(Connection.Session);
                var result = action.Result.Replace("\n", Environment.NewLine);
            }
        }

        private void AssignVgpu()
        {
            if (assignOrRemoveVgpu)
            {
                var newvGpus = new List<VGPU>();
                foreach (var vGpu in vGpus)
                {
                    newvGpus.Add(new VGPU
                    {
                        GPU_group = new XenRef<GPU_group>(vGpu.GPU_group.opaque_ref),
                        type = new XenRef<VGPU_type>(vGpu.type.opaque_ref),
                        device = vGpu.device
                    });
                }
                var action = new GpuAssignAction(VM, newvGpus);
                action.RunSync(Session);
            }
        }

        private void CopyBiosStrings()
        {
            if (CopyBiosStringsFrom != null && Template.DefaultTemplate())
            {
                VM.copy_bios_strings(Session, this.VM.opaque_ref, CopyBiosStringsFrom.opaque_ref);
            }
        }

        private void SetXenCenterProperties()
        {
            VM.IsBeingCreated = true;
            XenAdminConfigManager.Provider.HideObject(VM.opaque_ref);
            AppliesTo.Add(VM.opaque_ref);
        }

        private void SetVMParams()
        {
            Description = Messages.SETTING_VM_PROPERTIES;
            XenAPI.VM.set_name_label(Session, VM.opaque_ref, NameLabel);
            XenAPI.VM.set_name_description(Session, VM.opaque_ref, NameDescription);
            ChangeVCPUSettingsAction vcpuAction = new ChangeVCPUSettingsAction(VM, VcpusMax, VcpusAtStartup);
            vcpuAction.RunSync(Session);

            // set cores-per-socket
            Dictionary<string, string> platform = VM.platform == null ?
                            new Dictionary<string, string>() :
                            new Dictionary<string, string>(VM.platform);
            platform["cores-per-socket"] = CoresPerSocket.ToString();
            VM.set_platform(Session, VM.opaque_ref, platform);

            // Check these values have changed before setting them, as they are RBAC protected
            if (HomeServerChanged())
                XenAPI.VM.set_affinity(Session, VM.opaque_ref, HomeServer != null ? HomeServer.opaque_ref : Helper.NullOpaqueRef);

            if (Template.memory_dynamic_min != MemoryDynamicMin || Template.memory_dynamic_max != MemoryDynamicMax || Template.memory_static_max != MemoryStaticMax)
                XenAPI.VM.set_memory_limits(Session, VM.opaque_ref, Template.memory_static_min, MemoryStaticMax, MemoryDynamicMin, MemoryDynamicMax);
        }

        private bool HomeServerChanged()
        {
            if (HomeServer == null)
            {
                return Template.affinity.opaque_ref != Helper.NullOpaqueRef;
            }
            return HomeServer.opaque_ref != Template.affinity.opaque_ref;
        }

        private void SetVMBootParams()
        {
            if (Template.IsHVM() && (Disks.Count == 0 || InsMethod == InstallMethod.Network)) // CA-46213
            {
                // boot from network
                Dictionary<string, string> hvm_params = VM.HVM_boot_params;
                hvm_params["order"] = GetBootOrderNetworkFirst();
                XenAPI.VM.set_HVM_boot_params(Session, VM.opaque_ref, hvm_params);
            }
            else if (IsEli() && InsMethod == InstallMethod.Network)
            {
                Dictionary<string, string> other_config = VM.other_config;
                string normal_url = IsRhel() ? NormalizeRepoUrlForRHEL(Url) : Url;
                other_config["install-repository"] = normal_url;
                XenAPI.VM.set_other_config(Session, VM.opaque_ref, other_config);
            }
            else if (IsEli() && InsMethod == InstallMethod.CD)
            {
                Dictionary<string, string> other_config = VM.other_config;
                other_config["install-repository"] = "cdrom";
                XenAPI.VM.set_other_config(Session, VM.opaque_ref, other_config);
            }

            if (!Template.IsHVM())
            {
                XenAPI.VM.set_PV_args(Session, VM.opaque_ref, PvArgs);
            }
            else if (BootMode != BootMode.NOT_AVAILABLE)
            {
                var hvm_params = VM.HVM_boot_params;
                hvm_params["firmware"] = BootMode != BootMode.BIOS_BOOT ? "uefi" : "bios";
                XenAPI.VM.set_HVM_boot_params(Session, VM.opaque_ref, hvm_params);

                var platform = VM.platform;
                platform["secureboot"] = BootMode == BootMode.UEFI_SECURE_BOOT ? "true" : "false";
                XenAPI.VM.set_platform(Session, VM.opaque_ref, platform);
            }
        }

        private bool IsEli()
        {
            return !Template.IsHVM() && Template.PV_bootloader == "eliloader";
        }

        private bool IsRhel()
        {
            string distro = VM.InstallDistro();
            return distro == "rhel41" || distro == "rhel44" || distro == "rhlike";
        }

        private string NormalizeRepoUrlForRHEL(string url)
        {
            Uri uri = new Uri(url);
            return uri.Scheme == "nfs" ? string.Format("nfs:{0}:{1}", uri.Host, uri.PathAndQuery) : url;
        }

        private void ProvisionVM()
        {
            Description = Messages.PROVISIONING_VM;
            RewriteProvisionXML();
            RelatedTask = XenAPI.VM.async_provision(Session, VM.opaque_ref);

            PollToCompletion(10, 60);
        }

        private void RewriteProvisionXML()
        {
            XmlNode xml = VM.ProvisionXml();

            if (xml == null)
                return;

            // set the new vm's provision xml: remove "disks" entry, as we are going to explicitly create all the disks
            Dictionary<string, string> other_config = VM.other_config;
            other_config.Remove("disks");
            XenAPI.VM.set_other_config(Session, VM.opaque_ref, other_config);
        }

        private void AddCdDrive()
        {
            if (Helpers.CustomWithNoDVD(Template))
                return; // we have skipped the install media page because we are a cutom template with no cd drive - the user doesnt want a cd drive

            Description = Messages.CREATE_CD_DRIVE;
            VBD cd_drive = null;
            foreach (VBD vbd in Connection.ResolveAll(VM.VBDs))
            {
                if (vbd.type != vbd_type.CD)
                    continue;

                if ("0123".IndexOf(vbd.userdevice) < 0)  // userdevice is not 0, 1, 2 or 3: these are the valid positions for CD drives
                    continue;

                cd_drive = vbd;
                break;
            }

            if (cd_drive == null)
            {
                cd_drive = CreateCdDrive();
            }

            if (!cd_drive.empty)
            {
                RelatedTask = VBD.async_eject(Session, cd_drive.opaque_ref);
                PollToCompletion(65, 67);
            }

            if (InsMethod == InstallMethod.CD && Cd != null) // obviously dont insert the empty cd
            {
                RelatedTask = VBD.async_insert(Session, cd_drive.opaque_ref, Cd.opaque_ref);
                PollToCompletion(67, 70);
            }
        }

        private VBD CreateCdDrive()
        {
            List<string> devices = AllowedVBDs;
            if (devices.Count == 0)
                throw new Exception(Messages.NO_MORE_USERDEVICES);
            VBD vbd = new VBD
            {
                bootable = InsMethod == InstallMethod.CD,
                empty = true,
                unpluggable = true,
                mode = vbd_mode.RO,
                type = vbd_type.CD,
                userdevice = devices.Contains("3") ? "3" : devices[0],
                VM = new XenRef<VM>(VM.opaque_ref)
            };
            RelatedTask = VBD.async_create(Session, vbd);
            PollToCompletion(60, 65);

            return Connection.WaitForCache(new XenRef<VBD>(Result));
        }

        private void AddDisks()
        {
            Description = Messages.CREATING_DISKS;
            List<VBD> vbds = Connection.ResolveAll(VM.VBDs);

            bool firstDisk = true;
            string suspendSr = null;

            double progress = 70;
            double step = 20.0 / (double)Disks.Count;
            foreach (DiskDescription disk in Disks)
            {
                VBD vbd = GetDiskVBD(disk, vbds);
                VDI vdi = null;
                if (vbd != null)
                {
                    vdi = Connection.Resolve<VDI>(vbd.VDI);
                }
                if (!DiskOk(disk, vbd))
                {
                    if (vbd != null)
                        vdi = MoveDisk(disk, vbd, progress, step);
                    else
                        vdi = CreateDisk(disk, progress, step);
                }

                if (vdi == null)
                    continue;

                if (vdi.name_description != disk.Disk.name_description)
                    VDI.set_name_description(Session, vdi.opaque_ref, disk.Disk.name_description);
                if (vdi.name_label != disk.Disk.name_label)
                    VDI.set_name_label(Session, vdi.opaque_ref, disk.Disk.name_label);

                if (firstDisk)
                {
                    //use the first disk to set the VM.suspend_SR
                    SR vdiSR = Connection.Resolve(vdi.SR);
                    this.firstSR = vdiSR;
                    if(vdiSR != null && !vdiSR.HBALunPerVDI())
                        suspendSr = vdi.SR;
                    firstDisk = false;
                }

                progress += step;
            }

			VM.set_suspend_SR(Session, VM.opaque_ref, suspendSr);
        }

        private VBD GetDiskVBD(DiskDescription disk, List<VBD> vbds)
        {
            foreach (VBD vbd in vbds)
            {
                if (disk.Device.userdevice == vbd.userdevice)
                    return vbd;
            }
            return null;
        }

        private bool DiskOk(DiskDescription disk, VBD vbd)
        {
            if (vbd == null)
                return false;

            VDI vdi = Connection.Resolve(vbd.VDI);

            return vdi != null && disk.Disk.SR.opaque_ref == vdi.SR.opaque_ref;
        }

        private VDI MoveDisk(DiskDescription disk, VBD vbd, double progress, double step)
        {
            string old_vdi_ref = vbd.VDI.opaque_ref;

            RelatedTask = XenAPI.VDI.async_copy(Session, vbd.VDI.opaque_ref, disk.Disk.SR.opaque_ref);
            PollToCompletion(progress, progress + 0.25 * step);
            AddVMHint(Connection.WaitForCache(new XenRef<VDI>(Result)));

            VDI new_vdi = Connection.Resolve(new XenRef<VDI>(Result));

            RelatedTask = XenAPI.VBD.async_destroy(Session, vbd.opaque_ref);
            PollToCompletion(progress + 0.25 * step, progress + 0.5 * step);

            RelatedTask = XenAPI.VDI.async_destroy(Session, old_vdi_ref);
            PollToCompletion(progress + 0.5 * step, progress + 0.75 * step);

            CreateVbd(disk, new_vdi, progress + 0.75 * step, progress + step, IsDeviceAtPositionZero(disk));
            return new_vdi;
        }

        /// <summary>
        /// Helper: Check if the disk is at the zeroth position in the VBD list
        /// </summary>
        /// <param name="disk"></param>
        /// <returns></returns>
        private bool IsDeviceAtPositionZero(DiskDescription disk)
        {
            return disk.Device.userdevice == "0";
        }

        /// <summary>
        /// Create a VDI/disk.
        /// If disk type is existing use the VDI in disk description
        /// Otherwise create a new disk (provision it from the SR)
        /// </summary>
        /// <param name="disk"></param>
        /// <param name="progress"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        private VDI CreateDisk(DiskDescription disk, double progress, double step)
        {
            VDI vdi;
            bool bootable = false;
            if(disk.Type == DiskDescription.DiskType.Existing)
                vdi = disk.Disk;
            else
            {
                vdi = CreateVdi(disk, progress, progress + 0.75 * step);
                bootable = IsDeviceAtPositionZero(disk) && InsMethod != InstallMethod.CD;
            }

            AddVMHint(vdi);
            CreateVbd(disk, vdi, progress + 0.75 * step, progress + step, bootable);
            return vdi;
        }

        private void AddVMHint(VDI vdi)
        {
            Dictionary<string, string> sm_config = VDI.get_sm_config(Session, vdi.opaque_ref);
            sm_config["vmhint"] = VM.opaque_ref;
            VDI.set_sm_config(Session, vdi.opaque_ref, sm_config);
        }

        private VDI CreateVdi(DiskDescription disk, double progress1, double progress2)
        {
            VDI vdi = new VDI();
            vdi.name_label = disk.Disk.name_label;
            vdi.name_description = disk.Disk.name_description;
            vdi.read_only = false;
            vdi.sharable = false;
            vdi.SR = disk.Disk.SR;
            vdi.type = disk.Disk.type;
            vdi.virtual_size = disk.Disk.virtual_size;
            vdi.sm_config = disk.Disk.sm_config;

            RelatedTask = XenAPI.VDI.async_create(Session, vdi);
            PollToCompletion(progress1, progress2);
            return Connection.WaitForCache(new XenRef<VDI>(Result));
        }

        /// <summary>
        /// Create a VBD
        ///
        /// ** vbd.bootable **
        /// 1. Windows ignores bootable flag
        /// 2. Eliloader changes the device "0" to bootable when booting linux
        /// </summary>
        /// <param name="disk"></param>
        /// <param name="vdi"></param>
        /// <param name="progress1"></param>
        /// <param name="progress2"></param>
        /// <param name="bootable">Set VBD.bootable to this value - see comments above</param>
        private void CreateVbd(DiskDescription disk, VDI vdi, double progress1, double progress2, bool bootable)
        {
            List<string> devices = AllowedVBDs;
            if (devices.Count == 0)
                throw new Exception(Messages.NO_MORE_USERDEVICES);
            VBD vbd = new VBD();
            vbd.SetIsOwner(true);
            vbd.bootable = bootable;
            vbd.empty = false;
            vbd.unpluggable = true;
            vbd.mode = vbd_mode.RW;
            vbd.type = vbd_type.Disk;
            vbd.userdevice = devices.Contains(disk.Device.userdevice) ? disk.Device.userdevice : devices[0];
            vbd.device = "";
            vbd.VM = new XenRef<VM>(VM.opaque_ref);
            vbd.VDI = new XenRef<VDI>(vdi.opaque_ref);
            RelatedTask = VBD.async_create(Session, vbd);
            PollToCompletion(progress1, progress2);
            Connection.WaitForCache(new XenRef<VBD>(Result));
        }

        private void AddNetworks()
        {
            // first of all we need to clear any vifs that we have cloned from the template
            double progress = 90;
            VIF vif;
            List<VIF> existingTemplateVifs = Connection.ResolveAll(VM.VIFs);
            double step = 5.0 / (double)existingTemplateVifs.Count;
            for (int i = 0; i < existingTemplateVifs.Count; i++)
            {
                vif = existingTemplateVifs[i];
                RelatedTask = XenAPI.VIF.async_destroy(Session, vif.opaque_ref);

                PollToCompletion(progress, progress + step);
                progress += step;
            }

            // then we add the ones the user has specified
            step = 5.0 / (double)Vifs.Count;
            for (int i = 0; i < Vifs.Count; i++)
            {
                vif = Vifs[i];
                List<string> devices = AllowedVIFs;
                VIF new_vif = new VIF();

                if (devices.Count < 1)
                {
                    // If we have assigned more VIFs than we have space for then don't try to create them
                    log.Warn("Tried to create more VIFs than the server allows. Ignoring remaining vifs");
                    return;
                }
                new_vif.device = devices.Contains(vif.device) ? vif.device : devices[0];
                new_vif.MAC = vif.MAC;
                new_vif.network = vif.network;
                new_vif.VM = new XenRef<VM>(VM.opaque_ref);
                new_vif.qos_algorithm_type = vif.qos_algorithm_type;
                new_vif.qos_algorithm_params = vif.qos_algorithm_params;
                RelatedTask = XenAPI.VIF.async_create(Session, new_vif);

                PollToCompletion(progress, progress + step);
                progress += step;

                Connection.WaitForCache(new XenRef<VIF>(Result));
            }
        }

        private List<string> AllowedVBDs
        {
            get
            {
                return new List<String>(XenAPI.VM.get_allowed_VBD_devices(Session, VM.opaque_ref));
            }
        }

        private List<string> AllowedVIFs
        {
            get
            {
                return new List<String>(XenAPI.VM.get_allowed_VIF_devices(Session, VM.opaque_ref));
            }
        }

        protected override void CleanOnError()
        {
            if (VM != null && !PointOfNoReturn && Connection.IsConnected)
            {
                try
                {
                    VMDestroyAction.DestroyVM(Session, VM, true);
                }
                catch (Exception e)
                {
                    // if the clean up has failed for whatever reason we just log it and give up.
                    log.Error(e);
                }
            }
        }

        private string GetBootOrderNetworkFirst()
        {
            // add "n" at the beginning of the order string
            if (VM.HVM_boot_params.ContainsKey("order"))
            {
                string order = VM.HVM_boot_params["order"].ToLower();
                int i = order.IndexOf("n");
                switch (i)
                {
                    case -1: return order.Insert(0, "n");
                    case 0: return order;
                    default: return order.Remove(i, 1).Insert(0, "n");
                }
            }
            else
            {
                return "ncd";
            }
        }
    }
    public class DiskDescription
    {
        public VDI Disk;
        public VBD Device;
        public DiskType Type;
        public enum DiskType { New, Existing }

        public DiskDescription(){}

        public DiskDescription(VDI disk, VBD device)
        {
            Disk = disk;
            Device = device;
            Type = DiskType.New;
        }
    }
}