text:
import { Injectable } from '@angular/core';
import { Observable, Observer, Subject, BehaviorSubject, Subscription } from 'rxjs/Rx';

import * as firebase from 'firebase';

import { Cluster } from './cluster';
import { ClusterData } from './cluster-data';
import { ClusterSerializerXML } from './cluster-serializer-xml';
import { Uid } from './uid';
import { User } from './user';
import { ASCII_US, uniqueClusterName, minimalEncode, minimalDecode } from './utils';
import { ClusterContent } from "app/cluster-content";
import { RuntimeEnvironment } from './runtime-environment';
import { FirebaseConfig } from './firebase-config';

// I'm thinking this thing stores serialized XML somewhere and retrieves it from somewhere.
//
// Maybe into a global variable (how do we set that up) and via a text field somewhere (how do we set that up)?  In
// future, a FireBase d/b, maybe?  Need to get credentials from user for FireBase.

/**
 * Makes several Observables available, which point to various parts of the persistent data store in Firebase.
 * See nosql.org to d/b structure.
 */
@Injectable()
export class PersistenceService
{
   /**
    * Key by which env. index is stored in localstorage.
    */
   private static readonly ENVIRONMENT_INDEX_KEY = 'environmentIndex';

   // ============================================  Public Data, Accessors  ============================================

   public get environments(): RuntimeEnvironment[] { return this._environments; }

   /**
    * Index of currently-active RuntimeEnvironment.
    */
   public get currentEnvironmentIndex(): number { return this._currentEnvironmentIndex; }
   public set currentEnvironmentIndex( anIndex: number)
   {
      if (anIndex < 0 || anIndex >= this.environments.length)
         throw new Error( `illegal index (${anIndex}); must be < ${this.environments.length}`);
      else
      {
         this._currentEnvironmentIndex = anIndex;
         if (localStorage)
            localStorage.setItem(PersistenceService.ENVIRONMENT_INDEX_KEY, anIndex.toString());
      }
   }

   public get loginFailures(): Subject<Error> { return this._loginFailures; }

   /**
    * Current User; may be null.
    */
   public get currentUser(): BehaviorSubject<User> { return this._curUser; }

   /**
    * The current cluster (which may not have been saved yet), as a Subject.
    */
   public get currentClusterSubject(): BehaviorSubject<Cluster> {
      return this._currentGeneratedCluster
         || this._currentPersistedCluster;
   }

   /**
    * The current cluster (which may not have been saved yet, and/or, in the case of a persisted cluster, may be out of
    * date).
    */
   public get currentCluster(): Cluster {
      return (this._currentGeneratedCluster && this._currentGeneratedCluster.value)
         || (this._currentPersistedCluster && this._currentPersistedCluster.value);
   }

   public set currentGeneratedCluster( aCluster: Cluster) {
      if (this._currentPersistedCluster || this._currentPersistedClusterSubscription)
      {
         if (this._currentPersistedClusterSubscription)
            this._currentPersistedClusterSubscription.unsubscribe();
         // TODO: unsubscribe or whatever needs to be done (the above is just a guess).
      }
      this._currentGeneratedCluster = new BehaviorSubject<Cluster>( aCluster);
   }

   /**
    * List cluster meadata objects sorted in the correct order (e.g., last edited by/when, notes, etc.).
    */
   public get clusterMetadata(): Observable<Cluster[]> { return this._clusterMetadata; }

   /**
    * Current cluster from persistent (possibly shared) store.
    */
   private get currentPersistedCluster(): BehaviorSubject<Cluster> { return this._currentPersistedCluster; }

   // =================================================  Private Data  =================================================

   /**
    * Map from cluster unique name to Cluster.  Zero or more of these clusters will have all data filled in (and not
    * necessarily up to date); the rest will have only metadata.
    */
   private _latestClusterMap: Map<string, Cluster>;

   private _firebaseConfigProd = {
      apiKey: 'AIzaSyBiNVpydoOUGJiIavCB3f8qvB6ARYSy_1E',
      authDomain: 'diaspora-21544.firebaseapp.com',
      databaseURL: 'https://diaspora-21544.firebaseio.com',
      projectId: "diaspora-21544",
      storageBucket: 'diaspora-21544.appspot.com',
      messagingSenderId: '222484722746'
   };

   /**
    * List of runtime environments (think "databases") against which this app can run.
    */
   private _environments: RuntimeEnvironment[] = [
      new RuntimeEnvironment("Development",
         new FirebaseConfig(
            "AIzaSyDvVUt19co9Pu_kIln7FeW1LIGlujj03Ts",
            "diaspora-dev.firebaseapp.com",
            "https://diaspora-dev.firebaseio.com",
            "diaspora-dev",
            "diaspora-dev.appspot.com",
            "35664389096"
         )),
      new RuntimeEnvironment("Production",
         new FirebaseConfig(
            this._firebaseConfigProd.apiKey,
            this._firebaseConfigProd.authDomain,
            this._firebaseConfigProd.databaseURL,
            this._firebaseConfigProd.projectId,
            this._firebaseConfigProd.storageBucket,
            this._firebaseConfigProd.messagingSenderId))
   ];

   private _currentEnvironmentIndex: number;

   // private _ui: any;            // Firebase ui
   private _db: firebase.database.Database;
   private _authProvider: firebase.auth.GoogleAuthProvider;
   private _googleAccessToken: firebase.auth.AuthCredential;

   /**
    * Temporary holder for data used in creating a new email user, will be purged upon successful authentication.
    */
   private _emailUser: User;

   /**
    * Sequence of login failures, as time goes by.
    */
   private _loginFailures = new BehaviorSubject<Error>( null);

   // private _userPromise: Promise<User>;

   // On "deferred" promises: this is for the situation in which, when we create the promise ("new Promise(...)"), we do
   // not start the asynchronous/blocking work that will result in promise fulfillment.  Instead, that work has either
   // already been started or will be started elsewhere/elsewhen.  So, we simply save off an object holding pointers to
   // the resolve/reject functions so we can call them later (which we do).  See the handling of
   // this._userPromiseDeferred in this service.
   //
   // See
   // http://stackoverflow.com/questions/31069453/creating-a-es6-promise-without-starting-to-resolve-it/31069505#31069505
   //
   // private _userPromiseDeferred: {resolve: any, reject: any};

   private _users: Observable<Map<string, User>>;
   private _latestUserMap: Map<string, User>;

//   /**
//    * List of names of clusters that are visible to the current user.
//    */
//   private _visibleClusters: BehaviorSubject<BehaviorSubject<Cluster>[]>;

   /**
    * Observable<Object>, in which each object has a property (probably a boolean, but could be an int) whose name
    * is the UID of a cluster and whose value is irrelevant.
    */
   // NOTE: Can't declare type Uuid as alias for string and have Typescript flag cases in which a non-Uuid is supplied here.
   // The type equivalence doesn't save us.
   private _visibleClusterUuids: Observable<Object>;

   private _visibleClusterMap: Map<Uid, Cluster>;
   private _visibleClusterMapSubject: BehaviorSubject<Map<Uid, Cluster>>;

   /**
    * Map from cluster unique name to a cluster, decorated as needed for processing ({@see SeenCluster} is the
    * decoration).
    */
   private _seenClusterMap: Map<string, SeenCluster> = new Map<string, SeenCluster>();

   private _clusterMetadata: BehaviorSubject<Cluster[]> = new BehaviorSubject<Cluster[]>(new Array<Cluster>());

   private _currentGeneratedCluster: BehaviorSubject<Cluster>;
   private _currentGeneratedClusterSubscription: Subscription;

   private _currentPersistedCluster: BehaviorSubject<Cluster>;
   private _currentPersistedClusterSubscription: Subscription;

   private _curUser: BehaviorSubject<User> = new BehaviorSubject<User>(null);

   private _initialized = false;

   private _xmlSerializer: ClusterSerializerXML;

   // =================================================  Constructors  =================================================

   constructor( )
   {
      const me = this.constructor.name + '.ctor(): ';
      // This thing is one of the very first objects constructed, by the DI mechanism, at app initialization.
      console.log( me + `=============================================================================================`);
   }

   // ================================================  Public Methods  ================================================

   /**
    * Initialize firebase and hook up AuthStateChanged event.
    */
   public init(): void
   {
      const me = this.constructor.name + '.init(): ';
      console.log( me);
      if (this._initialized)    // Probably not threadsafe, but I'll think about that tomorrow.  After all, tomorrow is another day.
      {
         console.log( me + 'already initialized');
         return;
      }

      if (localStorage)
      {
         let envIxStr = localStorage.getItem( PersistenceService.ENVIRONMENT_INDEX_KEY);
         if (envIxStr == null)
            this._currentEnvironmentIndex = 0;
         else
            this._currentEnvironmentIndex = Number.parseInt( envIxStr);
      }
      else
         this._currentEnvironmentIndex = 0;

      this._xmlSerializer = new ClusterSerializerXML();

      // firebase.initializeApp( this._firebaseConfigProd);

      // // this._userPromise = new Promise(
      // //    ( resolve, reject) => this._userPromiseDeferred = {resolve: resolve, reject: reject});

      // firebase.auth().onAuthStateChanged( this.authStateChanged.bind( this), this.authError.bind( this));

      this._initialized = true;
      console.log( me + 'initialized');
   }

   public setEnvironment( anEnvironment: RuntimeEnvironment): void
   {
      let alreadyInitialized;
      let app: firebase.app.App;
      try
      {
         app = firebase.app();
         if (app && app.options['projectId'] == anEnvironment.firebaseConfig.projectId)
            alreadyInitialized = true;
         else
            alreadyInitialized = false;
      }
      catch (err)
      {
         if (err.code == 'app/no-app')
         {
            alreadyInitialized = false;
         }
         else throw err;
      }
      if (alreadyInitialized)
      {
         // Do nothing; we're good
      }
      else
      {
         if (app)
         {
            this._db = null;
            app.delete().then(() => this._initApp(anEnvironment));
         }
         else
            this._initApp(anEnvironment);
      }
   }

   private _initApp( anEnvironment: RuntimeEnvironment): void
   {
         firebase.initializeApp(anEnvironment.firebaseConfig);
         firebase.auth().onAuthStateChanged(this.authStateChanged.bind(this), this.authError.bind(this));
   }

   // ------------------------------------------------  Authentication  ------------------------------------------------

   /**
    * Returns a User object for the given uid. May return null.
    */
   public getUser( aUid: string): User
   {
      let retval: User;
      if (this._latestUserMap)
         retval = this._latestUserMap.get( aUid);
      return retval;
   }

   /**
    * Initiate login to Firebase.
    */
   public login(): void
   {
      const me = this.constructor.name + ".login(): ";
      console.log( me);
      this._loginWithPopup();
   }

   /**
    * Creates a new user account having the given email address and password.
    * @param anEmail
    * @param aPassword
    */
   public createUserWithEmailAndPassword(anEmail: string, aPassword: string, aUserName: string): void
   {
      const me = this.constructor.name + '.createUserWithEmailAndPassword(): ';
      this._emailUser = new User(null, aUserName, anEmail, null);
      firebase.auth().createUserWithEmailAndPassword(anEmail, aPassword)
         .catch( this._raiseLoginError.bind( this));
   }

   /**
    * Signs in to the user account having the given email address, using the given password.
    * @param anEmail
    * @param aPassword
    */
   public signInWithEmailAndPassword(anEmail: string, aPassword: string): void
   {
      const me = this.constructor.name + '.signInWithEmailAndPassword(): ';
      console.log( me);
      firebase.auth().signInWithEmailAndPassword(anEmail, aPassword ? aPassword : '')
         .catch( this._raiseLoginError.bind( this));
   }

   public sendForgottenEmailPassword(anEmailAddress: string): void
   {
      const me = this.constructor.name + '.sendForgottenEmailPassword(): ';
      console.log(me + `Requesting password reset for ${anEmailAddress}`);
      if (anEmailAddress)
         firebase.auth().sendPasswordResetEmail(anEmailAddress).then(
            (function (obj: any)
            {
               console.log(`successfully sent password reset request, result = ${obj}`);
               // Hack to get feedback to user: raise login error.
               this._raiseLoginError(
                  new Error(`Sent password reset email to ${anEmailAddress}; check your spam folder.
                     (This is not actually an error, unless you consider forgetting your password an error.)`));
            }).bind(this),
            this._raiseLoginError.bind(this)); // error
      else
         this._raiseLoginError(new Error(
            'You need to specify an email address so we know where to send a password reset email.'));
   }

   public logout()
   {
      const me = this.constructor.name + '.logout(): ';
      // alert( "logging out");
      console.log( me);
      firebase.auth().signOut().then( function() {
         console.log( 'signout successful');
      }).catch( function( anError: Error) {
         console.log( `signout error: ${anError.message}`);
      });
   }

   // public get user(): Promise<User>
   // {
   //    return this._userPromise;
   // }

   // -------------------------------------------------  Cluster Data  -------------------------------------------------

   /**
    * Ensure that this service actually has a cluster (which may be en empty dumy).
    */
   public ensureCluster(): void
   {
      if (this.currentCluster)
      {
         // Do nothing
      }
      else
      {
         // Just make one up!
         this._currentGeneratedCluster = new BehaviorSubject( new Cluster());
      }
   }

   /**
    * Initiate a request to the back end to load the cluster.
    *
    * @param aUniqueName Minimally-encoded cluster name + ASCII US + user uid
    */
   public loadCluster( aUniqueName: string): void
   {
      const me = this.constructor.name + '.loadCluster(): ';
      // let uniqueName = JSON.stringify( minimalEncode( aUniqueName));
      // const uniqueName = encodeURIComponent( aUniqueName);
      console.log( me + `loading ${aUniqueName}`);
      // if (this._currentPersistedCluster || this._currentPersistedClusterSubscription)
      // {
         if (this._currentPersistedClusterSubscription)
            this._currentPersistedClusterSubscription.unsubscribe();
         if (this._currentGeneratedClusterSubscription)
         {
            this._currentGeneratedClusterSubscription.unsubscribe();
            this._currentGeneratedClusterSubscription = null;
         }
         if (this._currentGeneratedCluster)
            this._currentGeneratedCluster = null;

         // TODO: unsubscribe or whatever needs to be done (the above is just a guess).
      // }
      this._currentPersistedCluster = new BehaviorSubject<Cluster>( new Cluster());
      this._currentPersistedClusterSubscription = this.makeDatabaseSnapshotObservable( `/clusterData/${aUniqueName}/data`)
         .map( s => this.parseClusterData( aUniqueName, s.val()))
         .multicast( this._currentPersistedCluster)
         .connect();
   }

   /**
    * Initiate a request to the back end to delete the given cluster.
    *
    * @param aUniqueName Same as that for {@see #loadCluster}.
    */
   public deleteCluster(aUniqueName: string): void
   {
      if (!this.currentUser.value)
         return;
      const me = this.constructor.name + '.deleteCluster(): ';
      // const uniqueName = encodeURIComponent( aUniqueName);
      console.log(me + `deleting ${aUniqueName}`);
      if (this._currentGeneratedClusterSubscription)
      {
         console.log(me + 'unsubscribing');
         this._currentPersistedClusterSubscription.unsubscribe();
         this._currentPersistedClusterSubscription = null;
      }

      if (!this._db) this._db = firebase.database();

      const updates = Object.create( null);

      // Note (TODO): this doesn't (yet) do any sort of reference counting, purging entire cluster only when this is the last
      // owner.  That'll have to be a later step.

      updates[`/users/${this.currentUser.value.uid}/clusters/${aUniqueName}`] = null;

      updates[`/clusters/${aUniqueName}/metadata`] = null;

      // These three permissions lists really should already be null, since I moved them over to /clusterData.
      // updates[`/clusters/${aUniqueName}/owners`] = null;
      // updates[`/clusters/${aUniqueName}/editors`] = null;
      // updates[`/clusters/${aUniqueName}/viewers`] = null;

      updates[`/clusterData/${aUniqueName}/data`] = null;
      updates[`/clusterData/${aUniqueName}/writers`] = null;
      updates[`/clusterData/${aUniqueName}/readers`] = null;

      this._db.ref().update( updates); // TODO: test to make sure permission failure in one location blocks entire transaction.
                                       // For example, if an editor (not an owner) tries to delete a cluster.
   }

   public saveCluster( aCluster: Cluster): void
   {
      const me = this.constructor.name + '.saveCluster()';
      console.log( me);
      // let uniqueName = JSON.stringify( minimalEncode( uniqueClusterName( aCluster, this.currentUser.value)));
      // const uniqueName = encodeURIComponent( uniqueClusterName( aCluster, this.currentUser.value));
      let uniqueName: string;
      if (aCluster.uid)
         uniqueName = aCluster.uid;
      else
      {
         uniqueName = uniqueClusterName( aCluster, this.currentUser.value);
         aCluster.uid = uniqueName; // Assumed to be a straight UUId.
      }
      if (! this._db)
         this._db = firebase.database();
      const dbRef = this._db.ref();

      // Metadata
      const clusterProps = {
            name: aCluster.name,
            lastAuthor: this.currentUser.value.uid,
            lastChanged: new Date( Date.now()),
            notes: aCluster.notes ? aCluster.notes : ''
      };

      // XML & other "full" cluster data
      this._xmlSerializer.cluster = aCluster;
      const xml = this._xmlSerializer.serialize();
      const owners = Object.create( null); // TODO: do we need this?
      owners[ `${this.currentUser.value.uid}`] = true;

      const updates = Object.create( null);

      // Clusters visible to current user: this one that we're saving, for sure.
      updates[`/users/${this.currentUser.value.uid}/clusters/${aCluster.uid}`] = true;
      updates[`/clusters/${uniqueName}/metadata`] = clusterProps;
      updates[`/clusterData/${uniqueName}/data/xml`] = xml;
      updates[`/clusterData/${uniqueName}/writers`] = owners;
      updates[`/clusterData/${uniqueName}/readers`] = owners;

      /* test data
      {
         'users': {
            'userUid' {
               'clusters': {
                  'clusterUid': true
               }
            }
         }
      }
      */

      console.log( `${me}: writing cluster data`);
      dbRef.update(updates).then(
         () => console.log(`${me}: update successful`),
         (err: firebase.FirebaseError) =>
         {
            console.log(`${me}: update failed; code = ${err.code}; msg = "${err.message}"`);
         }
      );
   }

   /**
    * Get cluster xml from some place wondrous and mysterious (like a server).
    */
   public getClusterXml(): string
   {
      return '';
   }

   // ===============================================  Private Methods  ================================================

   // ------------------------------------------------  Authentication  ------------------------------------------------

   private _loginWithPopup(): void
   {
      const me = this.constructor.name + '._loginWithPopup(): ';
      if (! this._authProvider)
         this._authProvider = new firebase.auth.GoogleAuthProvider();
      firebase.auth().signInWithPopup( this._authProvider).then(function (result)
      {
         // This gives you a Google Access Token. You can use it to access the Google API.
         const token = result.credential.accessToken;
         // The signed-in user info.
         const user = result.user;
         // ...
      }).catch(function (error: any)
      {
         // Handle Errors here.
         const errorCode = error.code;
         const errorMessage = error.message;
         // The email of the user's account used.
         const email = error.email;
         // The firebase.auth.AuthCredential type that was used.
         const credential = error.credential;
         alert( me + `Error: code = ${errorCode}; msg = ${errorMessage}\nemail = ${email}; credential = ${credential}`);
      });
   }

   private _loginWithRedirect(): void
   {
      const me =  this.constructor.name + '.login(): ';
      console.log( me);
      if (! this._authProvider)
         this._authProvider = new firebase.auth.GoogleAuthProvider();
      console.log( me + 'signing in');
      firebase.auth().signInWithRedirect( this._authProvider);
      // alert( "about to process redirect result");
      firebase.auth().getRedirectResult().then( (function( result: firebase.auth.UserCredential) {
         if (result.credential) {
            this._googleAccessToken = result.credential;
            console.log( me + `accessToken = "${this._googleAccessToken}`);
         }
         this._user = result.user;
         console.log( me + `logged in user "${this._user}"`);
         // alert( "login done");
      }).bind( this)).catch( (function( error: Error) {
         console.log( `${me} ${error.message}`); }).bind( this));
      console.log( me + 'done');
   }

   private _raiseLoginError( anErrorObj: any): void
   {
      const me = this.constructor.name + '._raiseLoginError(): ';
      console.log(me + `Error siging in: ${anErrorObj.code}: ${anErrorObj.message}`);
      const newError = new Error(anErrorObj.message);
      if (anErrorObj.code)
         newError.name = anErrorObj.code;
      this._loginFailures.next(newError);
   }

   private authStateChanged( aFirebaseUser: firebase.User): void
   {
      const me = this.constructor.name + '.authStateChanged(): ';
      // let user: User;
      if (aFirebaseUser)
      {
         const newUser = new User( aFirebaseUser.uid,
                          aFirebaseUser.displayName || aFirebaseUser.email || aFirebaseUser.uid,
                          aFirebaseUser.email,
                          new Date( Date.now()));
         console.log( me + `User logged in: ${newUser} with provider ${aFirebaseUser.providerId}`);
         if (this._emailUser)
         {
            // Temp. data from creating new email user -- transfer to newUser object and purge.
            newUser.name = this._emailUser.name;
            this._emailUser = null;
         }
         else
         {
            if (aFirebaseUser.displayName)
            {
               // Do nothing -- user came in with a display name, so assume it's good.
            }
            else
            {
               // We don't really care about the provider id here -- if there's no display name, we need to try to get it.
               newUser.isDisplayNameNeeded = true;
               console.log(me +
                  `Firebase user uid ${aFirebaseUser.uid} has displayName "${aFirebaseUser.displayName}" and email ${aFirebaseUser.email}`);
               console.log(me + '---- provider data:');
               for (const providerData of aFirebaseUser.providerData)
               {
                  console.log(me + `displayName\t: ${providerData.displayName}`);
                  console.log(me + `email\t: ${providerData.email}`);
                  console.log(me + `photoURL\t: ${providerData.photoURL}`);
                  console.log(me + `providerId\t: ${providerData.providerId}`);
                  console.log(me + `uid\t: ${providerData.uid}`);
               }
            }
         }
         this._curUser.next( newUser);
         if (newUser.uid)
         {
            if (! this._db) this._db = firebase.database();
            const dbRef = this._db.ref();
            console.log( me + `dbRef = ${dbRef}`);
            // userPublicProps: publicly-readable data for a user
            const userPublicProps = { name: newUser.name };
            // userProps: private data for a user.
            // const userProps = { email: newUser.email,
            //                   lastLogin: newUser.lastLogin.toISOString(),
            //                   timeZoneOffset: newUser.lastLogin.getTimezoneOffset()
            //                 };
            const updates = Object.create( null);
            if (newUser.isDisplayNameNeeded)
            {
               // Do nothing -- don't overwrite whatever's in the database with whatever garbage is in the user's current display name.
            }
            else
            {
               updates[`/usersPublic/${newUser.uid}`] = userPublicProps;
            }
            updates[`/users/${newUser.uid}/email`] = newUser.email;
            updates[`/users/${newUser.uid}/lastLogin`] = newUser.lastLogin;
            updates[`/users/${newUser.uid}/timeZoneOffset`] = newUser.lastLogin.getTimezoneOffset();
            dbRef.update( updates); // Performs insert if key doesn't exist, so that's good.

            this.connectToDatabase( newUser); // Now go get the clusters available to the current user.
         }
         else
            console.log( me + `WARNING: no uid for user ${newUser.name}`);
      }
      else
      {
         console.log( me + 'auth state changed, but passed user is null or empty, assuming logged out');
         this._curUser.next( null);
         // this._clusterMetadata.next( new Array<Cluster>()); // Once we purge this list, we don't get further
                                                               // notifications if the user logs back in, so there's no
                                                               // easy way to get it back.
      }
      // this._userPromiseDeferred.resolve( this._curUser); // We know _userPromiseDeferred won't be null because we create it
      //                                                 // before hooking up this event handler.
      this._loginFailures.next( null); // Auth state changed ==> no errors.  Authentication failures will not change the auth state.
   }

   private authError( aFirebaseAuthError): void
   {
      const me = this.constructor.name + '.authError(): ';
      console.log( me + `auth error: ${aFirebaseAuthError.message}`);
      this._curUser.error( new Error( `${me} FireBase authentication error: ${aFirebaseAuthError.message}`));
      // this._userPromiseDeferred.reject( aFirebaseAuthError);
   }

   // ---------------------------------------------------  Database  ---------------------------------------------------
   // - - - - - - - - - - - - - - - - - - -  (first user data, then cluster data)  - - - - - - - - - - - - - - - - - - -

   /**
    * Establish initial d/b connections. Note that initial connections may result in Observables/Promises which will
    * result in further connection requests.
    */
   private connectToDatabase( aUser: User)
   {
      const me = this.constructor.name + '.connectToDatabase(): ';
      if (aUser && aUser.uid)
      {
         this._db = firebase.database();
         console.log( me + `initialized firebase, db = "${this._db}"`);

         if (this._visibleClusterMap == null)
            this._visibleClusterMap = new Map<Uid, Cluster>();
         if (this._visibleClusterMapSubject == null)
         {
            this._visibleClusterMapSubject = new BehaviorSubject<Map<Uid, Cluster>>( this._visibleClusterMap);
            this._visibleClusterMapSubject.debounceTime( 300)
               .subscribe( m => this.sortAndPublishMetadata( m));
         }

         // TODO: make this a BehaviorSubject<Map<string,Cluster>>.
         // this._visibleClusters = new BehaviorSubject<BehaviorSubject<Cluster>[]>(new Array<BehaviorSubject<Cluster>>());
         // this._visibleClusters.subscribe( clusters => this.handleVisibleClusterListChange( clusters));

         /* this._visibleClusterUuids = */ this.makeDatabaseSnapshotObservable( `/users/${aUser.uid}/clusters`)
            .map( s => <Object> s.val()) // Object of cluster uuids
            .subscribe( uidObject => this.handleVisibleClusterListChange( uidObject))
            ;

//         // $uid/clusters is a list of unique names
//         let visibleClusterNamesSubscription
//            = this.makeDatabaseSnapshotObservable( `/users/${aUser.uid}/clusters`)
//            .map( s => { let uniqueNamesObj = s.val();
//                         let names = new Array<BehaviorSubject<Cluster>>();
//                         for (let uniqueName in uniqueNamesObj)
//                         {
//                            let cluster = this._clusterObservable[uniqueName].cluster;
//                            if (! cluster)
//                            {
//                               cluster = new Cluster();
//                               cluster.uid = uniqueName;
//                            }
//                            names.push( new BehaviorSubject<Cluster>( cluster));
//                         }
//                         return names;
//                       })
//            .multicast( this._visibleClusters)
//            .connect();

         // TODO: keep cluster metadata, but build differently.  Subscribe to each cluster separately, and provide next
         // result appropriately.  So... change in xml only, no next observable, but change in metadata ==> next result.
         // Change in _visbibleClusterNames almost certainly means at least a change in metadata ROWS (insert, delete).
      //    const clusterMetadataSubscription = this.makeDatabaseSnapshotObservable( '/clusters')
      //       .map( s => this.parseMetadata( s.val()))
      //       .multicast( this._clusterMetadata) // Uses the given Subject to create an Observable that can be subscribed
      //                                          //   to multiple times w/out re-triggering the sequence.
      //       .connect();                        // Actually starts the base Observable running, with updates to the
      //                                          //   subject.

         this._users = this.makeDatabaseSnapshotObservable( '/usersPublic').map( s => this.parseUsers( s.val()));
         this._users.subscribe( map => {this._latestUserMap = map; this.getDisplayNameFromUserMap(); });

         // TODO: make Behavior Subject containing cluster arrays?  Answer: YES, probably a good idea.  Then we wouldn't
         // need to bother with this "latest" junk, because a BehaviorSubject will always have the latest value.

         // let subscription = this._clusterNamesObservable.subscribe(
         //    (snapshot: firebase.database.DataSnapshot) => this.clusterNamesValueChanged( snapshot)
         //    ,(err) => this.firebaseError( err) // Doesn't work.
         // );
      }
      else
         console.log( me + 'WARNING: current user not yet initialized; cannot establish references to user-specific data');
   }

   /**
    * If required, try to get the current user's display name from the public data map.
    */
   private getDisplayNameFromUserMap(): void
   {
      const me = this.constructor.name + '.getDisplayNameFromUserMap(): ';
      const curUser = this._curUser ? this._curUser.value : null;
      if (curUser && curUser.isDisplayNameNeeded)
      {
         const userFromPublicMap = this._latestUserMap.get( curUser.uid);
         if (userFromPublicMap)
         {
            console.log( me + `Overwriting current user name (${curUser.name}) with "${userFromPublicMap.name}"`);
            // Overwrite whatever junk was in the current user's 'name' property (probably an email address or even a uid).
            curUser.name = userFromPublicMap.name;
            this._curUser.next( curUser); // Publish
            // At this point, we really should turn off curUser.isDisplayNameNeeded, but leaving it on allows to change
            // user display names on the fly, so what the heck.  If it becomes a performance problem, we can turn it off.
         }
      }
   }

   /**
    * Transforms incoming object, keyed by uid and having values from the public user info section of the d/b (e.g.,
    * property 'name' (not 'displayName')) into User objects having the corresponding properties (and only those properties).
    * @param aSnapshot
    */
   private parseUsers( aSnapshot: Object): Map<string, User> {
      const me = this.constructor.name + '.parseUsers(): ';
      const retval = new Map<string, User>();
      for (const uid in aSnapshot)
      {
         if (aSnapshot.hasOwnProperty(uid))
         {
            const user = aSnapshot[uid];
            user.uid = uid;
            retval.set(uid, user);
         }
      }
      console.log( me + `snapshot contains ${retval.size} users`);
      return retval;
   }

   // - - - - - - - - - - - - - - - - - - - - - - - - -  Cluster Data  - - - - - - - - - - - - - - - - - - - - - - - - -

   /**
    * Called when the list of names of clusters visible to the current user has changed, with the new list of Cluster
    * subjects.  Will drop subscriptions for deleted clusters and start new ones for new clusters.  Subscriptions for
    * existing clusters will continue unchanged.
    *
    * @param aClusterUidsObject DataSnapshot value whose properties are the currently visible cluster uuids.
    */
   private handleVisibleClusterListChange( aClusterUidsObject: Object): void
   {
      const me = this.constructor.name + '.handleVisibleClusterListChange(): ';
      console.log( me);
      // We're using the _seenClusterMap to manage subscriptions (new ones and unsubscribing from deleted clusters).
      this._seenClusterMap.forEach( sc => {sc.seen = false; });
      for (const clusterUid in aClusterUidsObject)
      {
         if (this._seenClusterMap.has( clusterUid))
            this._seenClusterMap.get( clusterUid).seen = true;
         else
         {
            // const newCluster = new Cluster();
            // newCluster.uid = clusterUid;
            // let clusterSubject = new BehaviorSubject<Cluster>( newCluster);
            const clusterSubscription = this.makeDatabaseSnapshotObservable( `/clusters/${clusterUid}/metadata`)
               .map( s =>
               {
                     const sval = s.val(); // sval == null ==> cluster has been deleted
                     const c = new Cluster( sval);
                     c.uid = clusterUid; // Note that cluster uid is not part of the snapshot object, but is instead the
                                         // root of the snapshot object.
                     return c;
                  })
               .subscribe( c => this.updateAndPublishClusterMap( c))
               ;
            const sc = new SeenCluster( true, /* newCluster, */ clusterSubscription);
            this._seenClusterMap.set( clusterUid, sc);
         }
      }
      const unseenKeys = new Array<string>();
      this._seenClusterMap.forEach( (val, key) =>
                                       {if (! val.seen) {
                                          unseenKeys.push( key);
                                          val.clusterSubscription.unsubscribe();
                                       }
                                       });
      for (const key of unseenKeys)
      {
         if (this._visibleClusterMap.has( key))
            this._visibleClusterMap.delete( key);
         this._seenClusterMap.delete( key);
      }
      if (unseenKeys.length)
         this._visibleClusterMapSubject.next( this._visibleClusterMap);

      // At this point, the only piece of data we're guaranteed to have is cluster uid; and that doesn't do any good to
      // sort on.
   }

   /**
    * Updates map of visible clusters (uid --> cluster) and publishes the updated map via mapSubject.next().
    * @param aCluster
    */
   // Will honor every event by updating the map and calling subject.next(newMap).  However, said subject will be
   // throttled before being sorted into a list for display.
   private updateAndPublishClusterMap( aCluster: Cluster): void
   {
      const me = this.constructor.name + '.updateAndPublishClusterMap(): ';
      console.log( me);
      this._visibleClusterMap.set( aCluster.uid, aCluster);
      this._visibleClusterMapSubject.next( this._visibleClusterMap);
   }

   /**
    * Sort given map into a list of cluster metadata objects and raise an event to cause them to be displayed.
    * @param aClusterMetadataMap
    */
   private sortAndPublishMetadata( aClusterMetadataMap: Map<Uid, Cluster>)
   {
      const me = this.constructor.name + '.sortAndPublishMetadata(): ';
      console.log( me);
      const metadataList = new Array<Cluster>();
      aClusterMetadataMap.forEach( (cluster: Cluster, uid: Uid) => metadataList.push( cluster));
      metadataList.sort( (a, b) =>
            {
                  if (a.name < b.name) return -1;
                  else if (a.name === b.name) return 0;
                  else return 1;
            });
      console.log( me + `metadataList has ${metadataList.length} items`);
      this._clusterMetadata.next( metadataList);
   }

//    /**
//     * Returns a map from cluster name to cluster metadata (e.g., last edited by/when, notes), which map is created from
//     * the given d/b snapshot.
//     */
//    private parseMetadata( aSnapshot: Object): Cluster[]
//    {
//       const me = this.constructor.name + ".parseMetadata(): ";
//       this._latestClusterMap = new Map<string, Cluster>();
//       const retval = Array<Cluster>();
//       for (const key in aSnapshot)
//       {
//          if (aSnapshot.hasOwnProperty( key))
//          {
//             // let keyTuple = minimalDecode( JSON.parse( key));
//             const keyTuple = decodeURIComponent( key);
//             let [name, uid] = keyTuple.split( ASCII_US, 2);
//             name = minimalDecode( name);
//             const clusterObj = <Cluster> aSnapshot[key]; // Note: just casting an Object (which is what I think aSnapshot[key]
//                                                       // is, since Firebase knows nothing about our class hierarchy) to
//                                                       // Cluster does not actually MAKE the thing a Cluster, it just
//                                                       // satisfies TypeScript's demand for type "congruence".
//             // clusterObj.lastAuthor = uid;
//             // clusterObj.name = name;

//             const cluster = new Cluster();
//             cluster.lastChanged = clusterObj.lastChanged;
//             cluster.lastAuthor = uid;
//             cluster.name = name;

//             retval.push( cluster);
//             this._latestClusterMap.set( key, cluster);
//          }
//       }
//       console.log( me + `aSnapshot contains ${retval.length} clusters`);
//       return retval;
//    }

   /**
    * Analogous to {@see #parseMetadata}, returns a Cluster object created from the given snapshot's "xml" property.
    */
   private parseClusterData( aUid: Uid, aSnapshot: Object): Cluster
   {
      const me = this.constructor.name + '.parseClusterData(): ';
      let retval: Cluster;
      if (aSnapshot)
      {
         const snapshot = <ClusterContent> aSnapshot;
         const serializer = new ClusterSerializerXML();
         const errors = serializer.deserialize( snapshot.xml);
         if (errors)
            console.log( me + `ERRORS:\n\t${errors}`);
         retval = serializer.cluster;
         retval.uid = aUid;
      }
      else
      {
         console.log( me + 'NOTE: data snapshot is null, so no cluster');
         retval = null;
      }
      return retval;
   }

   // - - - - - - - - - - - - - - - - - - - -  Private Database Utility Methods  - - - - - - - - - - - - - - - - - - - -

   /**
    * Makes an Observable of DataSnapshots out of a Firebase node, so the app can subscribe to new snapshots as they are
    * available.
    */
   private makeDatabaseSnapshotObservable( aNoSqlTreeNodeName: string): Observable<firebase.database.DataSnapshot>
   {
      if (! this._db) this._db = firebase.database();
      const dbRef = this._db.ref( aNoSqlTreeNodeName);
      const retval = <Observable<firebase.database.DataSnapshot>> Observable.fromEventPattern(
         (function addHandler( h: (a: firebase.database.DataSnapshot, b?: string) => any) {
            // Need to explicitly bind to firebaseError here because there's no easy way (that I can tell) to
            // generate/catch errors using the Observable subscription.
            dbRef.on( 'value', h, this.firebaseError); }).bind(this),
         function delHandler( h: (a: firebase.database.DataSnapshot, b?: string) => any) {
            dbRef.off( 'value', h);
         }
         // ,(aSnapshot: firebase.database.DataSnapshot) => aSnapshot
      );
      return retval
         // .map((s,i) => <firebase.database.DataSnapshot>s)
      ;
   }

   /**
    * Records that a FireBase error has occurred.  (Doesn't do a whole lot more than that right now.)
    */
   private firebaseError( anError: Error): void
   {
      const me = 'PersistenceService.firebaseError(): '; // this.constructor.name + ".firebaseError(): ";
      console.log( me + `firebaseError(): ` + anError.message);
      // if (anError.message.match( /^permission_denied/))
      //    this.login();
   }

}

// =================================================  Helper Classes  ==================================================

/**
 * A tuple decorating a cluster with a "seen" boolean for processing.
 */
class SeenCluster
{
      /**
       *
       * @param seen True iff cluster has been seen during processing
       * @param cluster The cluster itself
       * @param clusterSubscription Subscription to cluster updates
       */
   constructor( public seen: boolean, /* public cluster: Cluster, */ public clusterSubscription: Subscription) {}
}


text:
/**
 * @author Nikos M. / https://github.com/foo123/
 *
 * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
 */

THREE.DataTextureLoader = THREE.BinaryTextureLoader = function () {

	// override in sub classes
	this._parser = null;

};

THREE.BinaryTextureLoader.prototype = {

	constructor: THREE.BinaryTextureLoader,

	load: function ( url, onLoad, onProgress, onError ) {

		var scope = this;

		var texture = new THREE.DataTexture( );

		var loader = new THREE.XHRLoader();
		loader.setResponseType( 'arraybuffer' );

		loader.load( url, function ( buffer ) {

			var texData = scope._parser( buffer );

			if ( !texData ) return;

			if ( undefined !== texData.image ) {

				texture.image = texData.image;

			} else if ( undefined !== texData.data ) {

				texture.image.width = texData.width;
				texture.image.height = texData.height;
				texture.image.data = texData.data;

			}

			texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : THREE.ClampToEdgeWrapping;
			texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : THREE.ClampToEdgeWrapping;

			texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : THREE.LinearFilter;
			texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : THREE.LinearMipMapLinearFilter;

			texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;

			if ( undefined !== texData.format ) {

				texture.format = texData.format;

			}
			if ( undefined !== texData.type ) {

				texture.type = texData.type;

			}

			if ( undefined !== texData.mipmaps ) {

				texture.mipmaps = texData.mipmaps;

			}

			if ( 1 === texData.mipmapCount ) {

				texture.minFilter = THREE.LinearFilter;

			}

			texture.needsUpdate = true;

			if ( onLoad ) onLoad( texture, texData );

		}, onProgress, onError );

		return texture;

	}

};

redpajama_set_name: RedPajamaGithub


text:
<?php
namespace ambassador\controllers;

use common\models\LoginForm;
use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

/**
 * Site controller.
 * It is responsible for displaying static pages, and logging users in and out.
 */
class SiteController extends AmbassadorController
{
    /**
     * Returns a list of behaviors that this component should behave as.
     *
     * @return array
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Declares external actions for the controller.
     *
     * @return array
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays the index (home) page.
     * Use it in case your home page contains static content.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Logs in the user if his account is activated,
     * if not, displays standard error message.
     *
     * @return string|\yii\web\Response
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest)
        {
            return $this->goHome();
        }

        // get setting value for 'Login With Email'
        $lwe = Yii::$app->params['lwe'];

        // if "login with email" is true we instantiate LoginForm in "lwe" scenario
        $lwe ? $model = new LoginForm(['scenario' => 'lwe']) : $model = new LoginForm() ;

        // everything went fine, log in the user
        if ($model->load(Yii::$app->request->post()) && $model->login('ambassador'))
        {
            return $this->goBack();
        }
        // errors will be displayed
        else
        {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the user.
     *
     * @return \yii\web\Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

}


text:
from numpy import pi, cos, sin, ravel, unravel_index

try:
    from scipy.spatial import cKDTree
except ImportError:
    print('The kdtree_fast method requires the scipy.spatial module.')
    print('Ignore this warning when using the tunnel_fast method.')

__author__ = 'kmu'

'''
The tunnel_fast and kdtree_fast methods are taken from the Unidata Python Workshop.
See (https://github.com/kmunve/unidata-python-workshop/blob/master/netcdf-by-coordinates.ipynb) for more information.
'''

def tunnel_fast(latvar,lonvar,lat0,lon0):
    '''
    Find closest point in a set of (lat,lon) points to specified point
    latvar - 2D latitude variable from an open netCDF dataset
    lonvar - 2D longitude variable from an open netCDF dataset
    lat0, lon0 - query point
    Returns iy,ix such that the square of the tunnel distance
    between (latval[iy,ix], lonval[iy,ix]) and (lat0, lon0)
    is minimum.

    :param latvar:
    :param lonvar:
    :param lat0:
    :param lon0:

    :return:

    '''
    rad_factor = pi/180.0 # for trignometry, need angles in radians
    # Read latitude and longitude from file into numpy arrays
    latvals = latvar[:] * rad_factor
    lonvals = lonvar[:] * rad_factor
    ny,nx = latvals.shape
    lat0_rad = lat0 * rad_factor
    lon0_rad = lon0 * rad_factor
    # Compute numpy arrays for all values, no loops
    clat,clon = cos(latvals),cos(lonvals)
    slat,slon = sin(latvals),sin(lonvals)
    delX = cos(lat0_rad)*cos(lon0_rad) - clat*clon
    delY = cos(lat0_rad)*sin(lon0_rad) - clat*slon
    delZ = sin(lat0_rad) - slat;
    dist_sq = delX**2 + delY**2 + delZ**2
    minindex_1d = dist_sq.argmin()  # 1D index of minimum element
    iy_min,ix_min = unravel_index(minindex_1d, latvals.shape)
    return iy_min,ix_min

def kdtree_fast(latvar,lonvar,lat0,lon0):
    '''
    :param latvar:
    :param lonvar:
    :param lat0:
    :param lon0:
    :return:
    '''
    rad_factor = pi/180.0 # for trignometry, need angles in radians
    # Read latitude and longitude from file into numpy arrays
    latvals = latvar[:] * rad_factor
    lonvals = lonvar[:] * rad_factor
    ny,nx = latvals.shape
    clat,clon = cos(latvals),cos(lonvals)
    slat,slon = sin(latvals),sin(lonvals)
    # Build kd-tree from big arrays of 3D coordinates
    triples = list(zip(ravel(clat*clon), ravel(clat*slon), ravel(slat)))
    kdt = cKDTree(triples)
    lat0_rad = lat0 * rad_factor
    lon0_rad = lon0 * rad_factor
    clat0,clon0 = cos(lat0_rad),cos(lon0_rad)
    slat0,slon0 = sin(lat0_rad),sin(lon0_rad)
    dist_sq_min, minindex_1d = kdt.query([clat0*clon0, clat0*slon0, slat0])
    iy_min, ix_min = unravel_index(minindex_1d, latvals.shape)
    return iy_min,ix_min

if __name__ == "__main__":
    print("...")


text:
var echo = require("../../echo")
    , RemoteEvents = require("remote-events")

var stream1 = echo("optional namespace")
    , stream2 = echo("optional namespace")
    , ee1 = new RemoteEvents()
    , ee2 = new RemoteEvents()

stream1.pipe(ee1.getStream()).pipe(stream1)
stream2.pipe(ee2.getStream()).pipe(stream2)

ee1.on("offer", function (peer, offer) {
    console.log("got offer", offer, "from peer", peer)
})

ee2.emit("offer", "peer id #222", "this is an offer")


text:
<?php
    $fetchFiletypes = mysqli_query( $con, "SELECT meta_value FROM " . TSA_DB_PREFIX . "settings WHERE meta_key='downloads_whitelist' LIMIT 1;" );
    $fetchPosts = mysqli_query( $con, "SELECT id, title FROM " . TSA_DB_PREFIX . "posts;" );
    $fetchUploadDirectory = mysqli_fetch_array( mysqli_query( $con, "SELECT meta_value FROM " . TSA_DB_PREFIX . "settings WHERE meta_key='downloads_location' LIMIT 1;" ) );
    $uploadDirectory = $fetchUploadDirectory['meta_value'];
    $fetchDownloads = mysqli_query( $con, "SELECT id, post_id, hash, filetype, original_file_name, size FROM " . TSA_DB_PREFIX . "downloads;" );
    $filetypesArray = mysqli_fetch_array( $fetchFiletypes );
    $wlFiletypes = json_decode( $filetypesArray['meta_value'], true );
    if( !empty( $_POST['post_id'] ) && !empty( $_FILES['file_upload'] ) && !empty( $uploadDirectory ) ) {
        $fileInfo = $_FILES['file_upload'];
        $originalFileName = $fileInfo['name'];
        $filesize = $fileInfo['size'];
        $fileHash = sha1( sprintf( "%s_%s", time(), $originalFileName ) );
        $filePathinfo = pathinfo( $originalFileName );
        $fileType = $filePathinfo['extension'];
        $post_id = intval( $_POST['post_id'] );
        if( !isset( $wlFiletypes[ $fileType ] ) ) {
            ?>

This filetype has not been whitelisted and is not allowed.

            <?php
        } elseif( !$post_id || mysqli_num_rows( mysqli_query( $con, "SELECT title FROM " . TSA_DB_PREFIX . "posts WHERE id='" . $post_id . "' LIMIT 1;" ) ) == 0 ) {
            ?>

This post is invalid or does not exist.

            <?php
        } else {
            if( returnBytes( ini_get( "upload_max_filesize" ) ) < $filesize || returnBytes( ini_get( "post_max_size" ) ) < $filesize ) {
                ?>

File is too big in filesize to be uploaded.

                <?php
            } else {
                $origName = mysqli_real_escape_string( $con, $originalFileName );
                $insertDl = mysqli_query( $con, "INSERT INTO " . TSA_DB_PREFIX . "downloads( post_id, hash, filetype, original_file_name, size, date ) VALUES( '" . $post_id . "', '" . $fileHash . "', '" . $fileType . "', '" . $origName . "', '" . $filesize . "', '" . date( "Y-m-d H:i:s" ) . "' );" );
                if( move_uploaded_file( $fileInfo['tmp_name'], $uploadDirectory . DIRECTORY_SEPARATOR . $fileHash . "." . $fileType ) && $insertDl ) {
                    ?>

Download has been successfully added.

                    <?php
                } else {
                    $checkError = mysqli_error( $con );
                    if( $checkError ) {
                        ?>

MySQL Error! <?php echo $checkError; ?>

                        <?php
                    } else {
                        ?>

Error moving uploaded file to downloads directory!

                        <?php
                    }
                }
            }
        }
    }

    if( !empty( $_POST['delete_dl_id'] ) ) {
        $deleteID = intval( $_POST['delete_dl_id'] );

        if( $deleteID ) {
            $checkDL = mysqli_query( $con, "SELECT post_id, hash, filetype, original_file_name FROM " . TSA_DB_PREFIX . "downloads WHERE id='" . $deleteID . "' LIMIT 1;" );
            if( mysqli_num_rows( $checkDL ) == 0 ) {
                ?>

This file does not exist.

                <?php
            } else {
                $dlInfo = mysqli_fetch_array( $checkDL );
                if( unlink( $uploadDirectory . DIRECTORY_SEPARATOR . $dlInfo['hash'] . "." . $dlInfo['filetype'] ) && mysqli_query( $con, "DELETE FROM " . TSA_DB_PREFIX . "downloads WHERE id='" . $deleteID . "' LIMIT 1;" ) ) {
                    ?>

<?php echo $dlInfo['original_file_name']; ?> was successfully deleted.

                    <?php
                } else {
                    $checkError = mysqli_error( $con );
                    if( $checkError ) {
                        ?>

MySQL Error: <?php echo $checkError; ?>

                        <?php
                    } else {
                        ?>

Unable to delete file from directory. Please make sure the web server has the correct permissions.

                        <?php
                    }
                }
            }
        } else {
            ?>

Invalid file ID.

            <?php
        }
    }

    if( empty( $uploadDirectory ) ) {
        ?>

Upload directory not specified! Please contact an admin and ask them to specify this in the admin panel or file uploading will not work.

        <?php
    }

    $fetchDownloads = mysqli_query( $con, "SELECT id, post_id, hash, filetype, original_file_name, size FROM " . TSA_DB_PREFIX . "downloads;" ); // Update after addition
?>

Add a download

        <form method="post" action="" enctype="multipart/form-data">

                Post to attach to:
                <select id="post_id" name="post_id" required="" class="form-control" required="">
                    <option selected="">Please select a post</option>
                    <?php
                        while( $row = mysqli_fetch_array( $fetchPosts ) ) {
                            ?>
                            <option value="<?php echo $row[ 'id' ]; ?>"><?php echo stripslashes( $row['title'] ); ?></option>
                            <?php
                        }
                    ?>
                </select>
                This is the post that the downloadable file will be "attached" to.

                File to upload:
                <input type="file" name="file_upload" id="file_upload" class="form-control" required="" />
                Allowed filetypes: <?php echo implode( ', ', array_keys( $wlFiletypes ) ); ?>

            <button type="submit" class="btn btn-success">Add file</button>
        </form>

Remove a download

        <form method="post" action="">

                Filename:
                <select name="delete_dl_id" id="delete_dl_id" class="form-control">
                    <option selected="">Please select file to delete</option>
                    <?php
                        while( $row = mysqli_fetch_array( $fetchDownloads ) ) {
                            $id = $row['id'];
                            $post_id = $row['post_id'];
                            $hash = $row['hash'];
                            $fileType = $row['filetype'];
                            $fileName = $row['original_file_name'];
                            $size = $row['size'];
                            if( !isset( $postTiles[ $post_id ] ) ) {
                                $fetchingTitle = mysqli_fetch_array( mysqli_query( $con, "SELECT title FROM " . TSA_DB_PREFIX . "posts WHERE id='" . $post_id . "' LIMIT 1;" ) );
                                $postTitles[ $post_id ] = $fetchingTitle['title'];
                            }
                            ?>
                            <option value="<?php echo $id; ?>"><?php echo $fileName; ?> (<?php echo $postTitles[ $post_id ]; ?>)</option>
                            <?php
                        }
                    ?>
                </select>

            <button class="btn btn-danger" type="submit" onclick="return confirm('Are you sure you want to delete this download? It will also delete the stored file.');">Delete download</button>
        </form>


text:
#ifndef HEAPAM_H
#define HEAPAM_H

#include "access/htup.h"
#include "access/sdir.h"
#include "access/skey.h"
#include "access/xlog.h"
#include "nodes/primnodes.h"
#include "storage/bufpage.h"
#include "storage/lock.h"
#include "utils/relcache.h"
#include "utils/snapshot.h"

/* "options" flag bits for heap_insert */
#define HEAP_INSERT_SKIP_WAL	0x0001
#define HEAP_INSERT_SKIP_FSM	0x0002

typedef struct BulkInsertStateData *BulkInsertState;

typedef enum
{
	LockTupleShared,
	LockTupleExclusive
} LockTupleMode;

/* ----------------
 *		function prototypes for heap access method
 *
 * heap_create, heap_create_with_catalog, and heap_drop_with_catalog
 * are declared in catalog/heap.h
 * ----------------
 */

/* in heap/heapam.c */
extern Relation relation_open(Oid relationId, LOCKMODE lockmode);
extern Relation try_relation_open(Oid relationId, LOCKMODE lockmode);
extern Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode);
extern Relation try_relation_openrv(const RangeVar *relation, LOCKMODE lockmode);
extern void relation_close(Relation relation, LOCKMODE lockmode);

extern Relation heap_open(Oid relationId, LOCKMODE lockmode);
extern Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode);
extern Relation try_heap_openrv(const RangeVar *relation, LOCKMODE lockmode);

#define heap_close(r,l)  relation_close(r,l)

/* struct definition appears in relscan.h */
typedef struct HeapScanDescData *HeapScanDesc;

/*
 * HeapScanIsValid
 *		True iff the heap scan is valid.
 */
#define HeapScanIsValid(scan) PointerIsValid(scan)

extern HeapScanDesc heap_beginscan(Relation relation, Snapshot snapshot,
			   int nkeys, ScanKey key);
extern HeapScanDesc heap_beginscan_strat(Relation relation, Snapshot snapshot,
					 int nkeys, ScanKey key,
					 bool allow_strat, bool allow_sync);
extern HeapScanDesc heap_beginscan_bm(Relation relation, Snapshot snapshot,
				  int nkeys, ScanKey key);
extern void heap_rescan(HeapScanDesc scan, ScanKey key);
extern void heap_endscan(HeapScanDesc scan);
extern HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction);

extern bool heap_fetch(Relation relation, Snapshot snapshot,
		   HeapTuple tuple, Buffer *userbuf, bool keep_buf,
		   Relation stats_relation);
extern bool heap_hot_search_buffer(ItemPointer tid, Buffer buffer,
					   Snapshot snapshot, bool *all_dead);
extern bool heap_hot_search(ItemPointer tid, Relation relation,
				Snapshot snapshot, bool *all_dead);

extern void heap_get_latest_tid(Relation relation, Snapshot snapshot,
					ItemPointer tid);
extern void setLastTid(const ItemPointer tid);

extern BulkInsertState GetBulkInsertState(void);
extern void FreeBulkInsertState(BulkInsertState);

extern Oid heap_insert(Relation relation, HeapTuple tup, CommandId cid,
			int options, BulkInsertState bistate);
extern HTSU_Result heap_delete(Relation relation, ItemPointer tid,
			ItemPointer ctid, TransactionId *update_xmax,
			CommandId cid, Snapshot crosscheck, bool wait);
extern HTSU_Result heap_update(Relation relation, ItemPointer otid,
			HeapTuple newtup,
			ItemPointer ctid, TransactionId *update_xmax,
			CommandId cid, Snapshot crosscheck, bool wait);
extern HTSU_Result heap_lock_tuple(Relation relation, HeapTuple tuple,
				Buffer *buffer, ItemPointer ctid,
				TransactionId *update_xmax, CommandId cid,
				LockTupleMode mode, bool nowait);
extern void heap_inplace_update(Relation relation, HeapTuple tuple);
extern bool heap_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid,
				  Buffer buf);

extern Oid	simple_heap_insert(Relation relation, HeapTuple tup);
extern void simple_heap_delete(Relation relation, ItemPointer tid);
extern void simple_heap_update(Relation relation, ItemPointer otid,
				   HeapTuple tup);

extern void heap_markpos(HeapScanDesc scan);
extern void heap_restrpos(HeapScanDesc scan);

extern void heap_sync(Relation relation);

extern void heap_redo(XLogRecPtr lsn, XLogRecord *rptr);
extern void heap_desc(StringInfo buf, uint8 xl_info, char *rec);
extern void heap2_redo(XLogRecPtr lsn, XLogRecord *rptr);
extern void heap2_desc(StringInfo buf, uint8 xl_info, char *rec);

extern XLogRecPtr log_heap_move(Relation reln, Buffer oldbuf,
			  ItemPointerData from,
			  Buffer newbuf, HeapTuple newtup);
extern XLogRecPtr log_heap_clean(Relation reln, Buffer buffer,
			   OffsetNumber *redirected, int nredirected,
			   OffsetNumber *nowdead, int ndead,
			   OffsetNumber *nowunused, int nunused,
			   bool redirect_move);
extern XLogRecPtr log_heap_freeze(Relation reln, Buffer buffer,
				TransactionId cutoff_xid,
				OffsetNumber *offsets, int offcnt);
extern XLogRecPtr log_newpage(RelFileNode *rnode, ForkNumber forkNum,
			BlockNumber blk, Page page);

/* in heap/pruneheap.c */
extern void heap_page_prune_opt(Relation relation, Buffer buffer,
					TransactionId OldestXmin);
extern int heap_page_prune(Relation relation, Buffer buffer,
				TransactionId OldestXmin,
				bool redirect_move, bool report_stats);
extern void heap_page_prune_execute(Buffer buffer,
						OffsetNumber *redirected, int nredirected,
						OffsetNumber *nowdead, int ndead,
						OffsetNumber *nowunused, int nunused,
						bool redirect_move);
extern void heap_get_root_tuples(Page page, OffsetNumber *root_offsets);

/* in heap/syncscan.c */
extern void ss_report_location(Relation rel, BlockNumber location);
extern BlockNumber ss_get_location(Relation rel, BlockNumber relnblocks);
extern void SyncScanShmemInit(void);
extern Size SyncScanShmemSize(void);

#endif   /* HEAPAM_H */


text:
class Download::Requesters::ProtectedArea < Download::Requesters::Base
  def initialize format, wdpa_id
    @format = format
    @wdpa_id = wdpa_id
  end

  def request
    unless ['ready', 'generating'].include? generation_info['status']
      DownloadWorkers::ProtectedArea.perform_async(@format, identifier)
    end

    json_response
  end

  def domain
    'protected_area'
  end

  private

  def identifier
    @wdpa_id
  end
end


text:
/******************************************************************************
	event_status_driver.h
	API for the events status driver.
	This file contains public API.
	mpaque 11Oct91

	Copyright 1991 NeXT Computer, Inc.

	Modified:

******************************************************************************/

#ifndef _DRIVERS_EVENT_STATUS_DRIVER_
#define _DRIVERS_EVENT_STATUS_DRIVER_

__BEGIN_DECLS

#include <mach/port.h>
#include <IOKit/hidsystem/IOLLEvent.h>
#include <IOKit/hidsystem/IOHIDTypes.h>
#include <AvailabilityMacros.h>

/*
 * Event System Handle:
 *
 * Information used by the system between calls to NXOpenEventSystem and
 * NXCloseEventSystem.  The application should not
 * access any of the elements of this structure.
 */
typedef mach_port_t NXEventHandle;

/* Open and Close */
NXEventHandle NXOpenEventStatus(void);
void NXCloseEventStatus(NXEventHandle handle);

/* Status */
extern NXEventSystemInfoType NXEventSystemInfo(NXEventHandle handle,
				char *flavor,
				int *evs_info,
				unsigned int *evs_info_cnt);
/* Keyboard */
extern void NXSetKeyRepeatInterval(NXEventHandle handle, double seconds);
extern double NXKeyRepeatInterval(NXEventHandle handle);
extern void NXSetKeyRepeatThreshold(NXEventHandle handle, double threshold);
extern double NXKeyRepeatThreshold(NXEventHandle handle);
extern void NXResetKeyboard(NXEventHandle handle);

/* Mouse */
extern void NXSetClickTime(NXEventHandle handle, double seconds);
extern double NXClickTime(NXEventHandle handle);
extern void NXSetClickSpace(NXEventHandle handle, _NXSize_ *area);
extern void NXGetClickSpace(NXEventHandle handle, _NXSize_ *area);
extern void NXResetMouse(NXEventHandle handle);

/*
* The following functions have been removed.
*
* NXIdleTime
* ÊÊÊÊSee CGEventSourceSecondsSinceLastEventType.
*
* NXSetKeyMapping
* NXKeyMappingLength
* NXGetKeyMapping
* ÊÊÊÊThese do not have a drop in replacement. ÊSee UCKeyTranslate.
*
* NXSetMouseScaling
* ÊÊÊÊSee IOHIDSetAccelerationWithKey and IOHIDSetMouseAcceleration.
*
* NXGetMouseScaling
* ÊÊÊÊSee IOHIDGetAccelerationWithKey and IOHIDGetMouseAcceleration.
*
* NXSetAutoDimThreshold
* NXSetAutoDimState
* ÊÊÊÊSee IOPMSetAggressiveness and kPMMinutesToDim.
*
* NXAutoDimThreshold
* NXAutoDimTime
* NXAutoDimState
* ÊÊÊÊSee IOPMGetAggressiveness and kPMMinutesToDim.
*
* NXSetAutoDimBrightness
* NXAutoDimBrightness
* NXSetScreenBrightness
* NXScreenBrightness
* ÊÊÊÊThis functionality is unsupported.
*/

__END_DECLS

#endif /*_DRIVERS_EVENT_STATUS_DRIVER_ */


text:
package org.apache.reef.vortex.api;

import org.apache.reef.annotations.Unstable;
import org.apache.reef.annotations.audience.ClientSide;
import org.apache.reef.annotations.audience.Public;
import java.util.List;

/**
 * Typed user function for Local Aggregation. Implement your functions using this interface.
 * @param <TOutput> output type of the aggregation function and the functions to-be-aggregated.
 */
@Public
@ClientSide
@Unstable
public interface VortexAggregateFunction<TOutput> {

  /**
   * Runs a custom local aggregation function on Tasklets assigned to a VortexWorker.
   * @param taskletOutputs the list of outputs from Tasklets on a Worker.
   * @return the aggregated output of Tasklets.
   * @throws Exception
   */
  TOutput call(List<TOutput> taskletOutputs) throws VortexAggregateException;
}


text:
AirChat
=======

LAN-based chat client.


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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 Microsoft.Azure.Commands.Scheduler.Test.ScenarioTests
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Microsoft.Azure.Commands.Common.Authentication;
    using Microsoft.Azure.Gallery;
    using Microsoft.Azure.Management.Authorization;
    using Microsoft.Azure.Management.Resources;
    using Microsoft.Azure.Management.Scheduler;
    using Microsoft.Azure.Subscriptions;
    using Microsoft.Azure.Test.HttpRecorder;
    using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
    using Microsoft.WindowsAzure.Commands.ScenarioTest;
    using LegacyTest = Microsoft.Azure.Test;

    public class SchedulerController
    {
        /// <summary>
        /// CSM test factory.
        /// </summary>
        private LegacyTest.CSMTestEnvironmentFactory _csmTestFactory;

        /// <summary>
        /// EnvironmentSetupHelper instance.
        /// </summary>
        private EnvironmentSetupHelper _helper;

        /// <summary>
        /// Authorization Api version.
        /// </summary>
        private readonly string AuthorizationApiVersion = "2014-07-01-preview";

        /// <summary>
        /// Gets or sets the ResourceManagementClient
        /// </summary>
        public ResourceManagementClient ResourceManagementClient { get; private set; }

        /// <summary>
        /// Gets or sets the SubscriptionClient.
        /// </summary>
        public SubscriptionClient SubscriptionClient { get; private set; }

        /// <summary>
        /// Gets or sets the AuthorizationManagementClient.
        /// </summary>
        public AuthorizationManagementClient AuthorizationManagementClient { get; private set; }

        /// <summary>
        /// Gets or sets the GalleryClient.
        /// </summary>
        public GalleryClient GalleryClient { get; private set; }

        /// <summary>
        /// Gets or sets the SchedulerManagementClient.
        /// </summary>
        public SchedulerManagementClient SchedulerManagementClient { get; private set; }

        /// <summary>
        /// Creates a new instance of workflow controller.
        /// </summary>
        public static SchedulerController NewInstance
        {
            get
            {
                return new SchedulerController();
            }
        }

        /// <summary>
        /// Initializes new instance of <see cref="Schedulercontroller"/> class.
        /// </summary>
        public SchedulerController()
        {
            this._helper = new EnvironmentSetupHelper();
        }

        /// <summary>
        /// RUns the PowerShell tests.
        /// </summary>
        /// <param name="scripts">Scripts to be executed.</param>
        public void RunPowerShellTests(params string[] scripts)
        {
            string callingClassType = TestUtilities.GetCallingClass(2);
            string mockName = TestUtilities.GetCurrentMethodName(2);
            RunPsTestScheduler(
                () => scripts,
                // no custom initializer
                null,
                // no custom cleanup
                null,
                callingClassType,
                mockName);
        }

        public void RunPsTestScheduler(
            Func<string[]> scriptBuilder,
            Action<LegacyTest.CSMTestEnvironmentFactory> initialize,
            Action cleanup,
            string callingClassType,
            string mockName)
        {
            var providers = new Dictionary<string, string>();
            providers.Add("Microsoft.Authorization", this.AuthorizationApiVersion);
            providers.Add("Microsoft.Resources", null);
            providers.Add("Microsoft.Features", null);
            providers.Add("Microsoft.Storage", null);

            var providersToIgnore = new Dictionary<string, string>();
            providersToIgnore.Add("Microsoft.Azure.Management.Resources.ResourceManagementClient", "2016-02-01");

            HttpMockServer.Matcher = new PermissiveRecordMatcherWithApiExclusion(ignoreResourcesClient: true, providers: providers, userAgents: providersToIgnore);
            HttpMockServer.RecordsDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SessionRecords");

            using(MockContext context = MockContext.Start(className: callingClassType, methodName: mockName))
            {
                this._csmTestFactory = new LegacyTest.CSMTestEnvironmentFactory();

                if (initialize != null)
                {
                    initialize(this._csmTestFactory);
                }

                SetupManagementClients(context);

                this._helper.SetupEnvironment(mode: AzureModule.AzureResourceManager);

                string callingClassName = callingClassType
                                    .Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries)
                                    .Last();

                this._helper.SetupModules(AzureModule.AzureResourceManager,
                             "ScenarioTests\\Common.ps1",
                             "ScenarioTests\\" + callingClassName + ".ps1",
                             _helper.RMProfileModule,
                             _helper.RMResourceModule,
                             _helper.GetRMModulePath(@"AzureRM.Scheduler.psd1"),
                             "AzureRM.Resources.ps1",
                             "AzureRM.Storage.ps1");

                try
                {
                    if (scriptBuilder != null)
                    {
                        var pScripts = scriptBuilder();

                        if (pScripts != null)
                        {
                            this._helper.RunPowerShellTest(pScripts);
                        }
                    }
                }
                finally
                {
                    if (cleanup != null)
                    {
                        cleanup();
                    }
                }
            }
        }

        /// <summary>
        /// Setup Mock clients.
        /// </summary>
        /// <param name="context"></param>
        private void SetupManagementClients(MockContext context)
        {
            this.ResourceManagementClient = GetResourceManagementClient();
            this.SubscriptionClient = GetSubscriptionClient();
            this.AuthorizationManagementClient = GetAuthorizationManagementClient();
            this.GalleryClient = GetGalleryClient();
            this.SchedulerManagementClient = GetSchedulerManagementClient(context);

            this._helper.SetupManagementClients(
                ResourceManagementClient,
                SubscriptionClient,
                AuthorizationManagementClient,
                GalleryClient,
                SchedulerManagementClient);
        }

        /// <summary>
        /// Creates a ResourceManagementClient instance.
        /// </summary>
        /// <returns>ResourceManagementClient instance.</returns>
        private ResourceManagementClient GetResourceManagementClient()
        {
           return LegacyTest.TestBase.GetServiceClient<ResourceManagementClient>(this._csmTestFactory);
        }

        /// <summary>
        /// Create a SubscriptionClient instance.
        /// </summary>
        /// <returns>SubscriptionClient instance.</returns>
        private SubscriptionClient GetSubscriptionClient()
        {
            return LegacyTest.TestBase.GetServiceClient<SubscriptionClient>(this._csmTestFactory);
        }

        /// <summary>
        /// Create an AuthorizationManagementClient instance.
        /// </summary>
        /// <returns>AuthorizationManagementClient instance.</returns>
        private AuthorizationManagementClient GetAuthorizationManagementClient()
        {
            return LegacyTest.TestBase.GetServiceClient<AuthorizationManagementClient>(this._csmTestFactory);
        }

        /// <summary>
        /// Creates GalleryClient instance.
        /// </summary>
        /// <returns>GalleryClient instance.</returns>
        private GalleryClient GetGalleryClient()
        {
            return LegacyTest.TestBase.GetServiceClient<GalleryClient>(this._csmTestFactory);
        }

        /// <summary>
        /// Creates SchedulerManagementClient based on mode setting.
        /// </summary>
        /// <param name="context">Context object.</param>
        /// <returns>SchedulerManagementClient instance.</returns>
        private SchedulerManagementClient GetSchedulerManagementClient(MockContext context)
        {
            return context.GetServiceClient<SchedulerManagementClient>(TestEnvironmentFactory.GetTestEnvironment());
        }
    }
}


text:
namespace Morph
{
    public class TypeLoadException : SystemException
    {
        const int Result = unchecked((int)0x80131522);

        // Fields
        private string className, assemblyName;

        // Constructors
        public TypeLoadException()
            : base("A type load exception has occurred.")
        {
            HResult = Result;
        }

        public TypeLoadException(string message)
            : base(message)
        {
            HResult = Result;
        }

        public TypeLoadException(string message, Exception inner)
            : base(message, inner)
        {
            HResult = Result;
        }

        internal TypeLoadException(string className, string assemblyName)
            : this()
        {
            this.className = className;
            this.assemblyName = assemblyName;
        }

        // Properties
        public override string Message
        {
            get
            {
                if (className != null)
                {
                    if ((assemblyName != null) && (assemblyName != String.Empty))
                        return "Could not load type '" + className + "' from assembly '" + assemblyName + "'.";
                    else
                        return "Could not load type '" + className + "'.";
                }
                else
                    return base.Message;
            }
        }

        public string TypeName
        {
            get
            {
                if (className == null)
                    return String.Empty;
                else
                    return className;
            }
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: garbi
 * Date: 3/11/15
 * Time: 3:20 PM
 */

// src/DispatcherBundle/Entity/LabServer.php
namespace DispatcherBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity
 * @ORM\Table(name="LabServer")
 */
class LabServer
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $Guid;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $name;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $institution;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $contact_name;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $contact_email;

    /**
     * @ORM\Column(type="string", length=500, nullable=true)
     */
    protected $description;

    /**
     * @ORM\Column(type="integer")
     */
    protected $owner_id;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $public_sub; //If true, anyone can subscribe to execute experiments for this lab server, otherwise only the owner is allowed to subscribe

    /**
     * @ORM\Column(type="boolean")
     */
    protected $active;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    protected $visible_in_catalogue; //if true owners allow it to be visible in the Website's catalogue

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $configuration; //If necessary, stores configuration of the lab in JSON, XML, etc.

    /**
     * @ORM\Column(type="boolean", nullable=false)
     */
    protected $singleEngine; //If true, only one experiment engine is allowed to connect to the lab server. Only in this case the service 'setLabConfiguration' is enabled!

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $opaqueData; //Optional field, used to transfer additional information if necessary.

    /**
     * @ORM\Column(type="string", length=35)
     */
    protected $dateCreated;

    /**
     * @ORM\Column(type="string", length=64)
     */
    protected $passKey;

    /**
     * @ORM\Column(type="string", length=64)
     */
    protected $initialPassKey;

    /**
     * @ORM\Column(type="string", length=10)
     */
    protected $type;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $labInfo;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $rlmsSpecificData; //Optional field, used to stope RLMS specific data

    /**
     * @ORM\Column(type="string", length=50)
     */
    protected $exp_category;

    /**
     * @ORM\Column(type="string", length=50)
     */
    protected $exp_name;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $useDataset;

    // Data used to federate requests to other ISA lab server
    /**
     * @ORM\Column(type="boolean")
     */
    protected $federate;

    /**
     * @ORM\Column(type="string", length=100, nullable=true)
     */
    protected $isaWsdlUrl;

    /**
     * @ORM\Column(type="string", length=100, nullable=true)
     */
    protected $isaIdentifier;

    /**
     * @ORM\Column(type="string", length=64, nullable=true)
     */
    protected $isaPasskeyToLabServer;

    public function setAll($data, $ownerId)
    {
        $this->Guid = $data['Guid'];
        $this->name = $data['name'];
        $this->institution = $data['institution'];
        $this->contact_name = $data['contact_name'];
        $this->contact_email = $data['contact_email'];
        $this->description = $data['description'];
        $this->owner_id = $ownerId;
        $this->active = $data['active'];
        //$this->visible_in_catalogue = $data['visible_in_catalogue'];
        $this->configuration = $data['configuration'];
        $this->singleEngine = $data['singleEngine'];
        $this->public_sub = false;
        $this->dateCreated = date('Y-m-d\TH:i:sP');
        $this->passKey = $data['passKey'];
        $this->initialPassKey = $data['initialPassKey'];
        $this->labInfo = $data['labInfo'];
        $this->type = $data['type'];
        $this->exp_category = $data['exp_category'];
        $this->exp_name = $data['exp_name'];
        $this->useDataset = $data['useDataset'];
        $this->federate = $data['federate'];
        $this->isaWsdlUrl = $data['isaWsdlUrl'];
        $this->isaIdentifier = $data['isaIdentifier'];
        $this->isaPasskeyToLabServer = $data['isaPasskeyToLabServer'];

    }

    public function updateAll($data)
    {
        $this->name = $data['name'];
        $this->institution = $data['institution'];
        $this->contact_name = $data['contact_name'];
        $this->contact_email = $data['contact_email'];
        $this->description = $data['description'];
        $this->active = $data['active'];
        //$this->visible_in_catalogue = $data['visible_in_catalogue'];
        $this->configuration = $data['configuration'];
        $this->singleEngine = $data['singleEngine'];
        $this->public_sub = false;
        $this->labInfo = $data['labInfo'];
        $this->exp_category = $data['exp_category'];
        $this->exp_name = $data['exp_name'];
        $this->useDataset = $data['useDataset'];
        $this->federate = $data['federate'];
        $this->isaWsdlUrl = $data['isaWsdlUrl'];
        $this->isaIdentifier = $data['isaIdentifier'];
        $this->isaPasskeyToLabServer = $data['isaPasskeyToLabServer'];
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set Guid
     *
     * @param string $guid
     * @return LabServer
     */
    public function setGuid($guid)
    {
        $this->Guid = $guid;

        return $this;
    }

    /**
     * Get Guid
     *
     * @return string
     */
    public function getGuid()
    {
        return $this->Guid;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return LabServer
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set institution
     *
     * @param string $institution
     * @return LabServer
     */
    public function setInstitution($institution)
    {
        $this->institution = $institution;

        return $this;
    }

    /**
     * Get institution
     *
     * @return string
     */
    public function getInstitution()
    {
        return $this->institution;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return LabServer
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set owner_id
     *
     * @param integer $ownerId
     * @return LabServer
     */
    public function setOwnerId($ownerId)
    {
        $this->owner_id = $ownerId;

        return $this;
    }

    /**
     * Get owner_id
     *
     * @return integer
     */
    public function getOwnerId()
    {
        return $this->owner_id;
    }

    /**
     * Set public_sub
     *
     * @param boolean $publicSub
     * @return LabServer
     */
    public function setPublicSub($publicSub)
    {
        $this->public_sub = $publicSub;

        return $this;
    }

    /**
     * Get public_sub
     *
     * @return boolean
     */
    public function getPublicSub()
    {
        return $this->public_sub;
    }

    /**
     * Set active
     *
     * @param boolean $active
     * @return LabServer
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Get active
     *
     * @return boolean
     */
    public function getActive()
    {
        return $this->active;
    }

    /**
     * Set visible_in_catalogue
     *
     * @param boolean $visibleInCatalogue
     * @return LabServer
     */
    public function setVisibleInCatalogue($visibleInCatalogue)
    {
        $this->visible_in_catalogue = $visibleInCatalogue;

        return $this;
    }

    /**
     * Get visible_in_catalogue
     *
     * @return boolean
     */
    public function getVisibleInCatalogue()
    {
        return $this->visible_in_catalogue;
    }

    /**
     * Set dateCreated
     *
     * @param \DateTime $dateCreated
     * @return LabServer
     */
    public function setDateCreated($dateCreated)
    {
        $this->dateCreated = $dateCreated;

        return $this;
    }

    /**
     * Get dateCreated
     *
     * @return \DateTime
     */
    public function getDateCreated()
    {
        return $this->dateCreated;
    }

    /**
     * Set configuration
     *
     * @param string $configuration
     * @return LabServer
     */
    public function setConfiguration($configuration)
    {
        $this->configuration = $configuration;

        return $this;
    }

    /**
     * Get configuration
     *
     * @return string
     */
    public function getConfiguration()
    {
        return $this->configuration;
    }

    /**
     * Set singleEngine
     *
     * @param boolean $singleEngine
     * @return LabServer
     */
    public function setSingleEngine($singleEngine)
    {
        $this->singleEngine = $singleEngine;

        return $this;
    }

    /**
     * Get singleEngine
     *
     * @return boolean
     */
    public function getSingleEngine()
    {
        return $this->singleEngine;
    }

    /**
     * Set opaqueData
     *
     * @param string $opaqueData
     * @return LabServer
     */
    public function setOpaqueData($opaqueData)
    {
        $this->opaqueData = $opaqueData;

        return $this;
    }

    /**
     * Get opaqueData
     *
     * @return string
     */
    public function getOpaqueData()
    {
        return $this->opaqueData;
    }

    /**
     * Set contact_name
     *
     * @param string $contactName
     * @return LabServer
     */
    public function setContactName($contactName)
    {
        $this->contact_name = $contactName;

        return $this;
    }

    /**
     * Get contact_name
     *
     * @return string
     */
    public function getContactName()
    {
        return $this->contact_name;
    }

    /**
     * Set contact_email
     *
     * @param string $contactEmail
     * @return LabServer
     */
    public function setContactEmail($contactEmail)
    {
        $this->contact_email = $contactEmail;

        return $this;
    }

    /**
     * Get contact_email
     *
     * @return string
     */
    public function getContactEmail()
    {
        return $this->contact_email;
    }

    /**
     * Set passKey
     *
     * @param string $passKey
     * @return LabServer
     */
    public function setPassKey($passKey)
    {
        $this->passKey = $passKey;

        return $this;
    }

    /**
     * Get passKey
     *
     * @return string
     */
    public function getPassKey()
    {
        return $this->passKey;
    }

    /**
     * Set labInfo
     *
     * @param string $labInfo
     * @return LabServer
     */
    public function setLabInfo($labInfo)
    {
        $this->labInfo = $labInfo;

        return $this;
    }

    /**
     * Get labInfo
     *
     * @return string
     */
    public function getLabInfo()
    {
        return $this->labInfo;
    }

    /**
     * Set initialPassKey
     *
     * @param string $initialPassKey
     * @return LabServer
     */
    public function setInitialPassKey($initialPassKey)
    {
        $this->initialPassKey = $initialPassKey;

        return $this;
    }

    /**
     * Get initialPassKey
     *
     * @return string
     */
    public function getInitialPassKey()
    {
        return $this->initialPassKey;
    }

    /**
     * Set type
     *
     * @param string $type
     * @return LabServer
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return string
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set rlmsSpecificData
     *
     * @param string $rlmsSpecificData
     * @return LabServer
     */
    public function setRlmsSpecificData($rlmsSpecificData)
    {
        $this->rlmsSpecificData = $rlmsSpecificData;

        return $this;
    }

    /**
     * Get rlmsSpecificData
     *
     * @return string
     */
    public function getRlmsSpecificData()
    {
        return $this->rlmsSpecificData;
    }

    /**
     * Set exp_category
     *
     * @param string $expCategory
     * @return LabServer
     */
    public function setExpCategory($expCategory)
    {
        $this->exp_category = $expCategory;

        return $this;
    }

    /**
     * Get exp_category
     *
     * @return string
     */
    public function getExpCategory()
    {
        return $this->exp_category;
    }

    /**
     * Set exp_name
     *
     * @param string $expName
     * @return LabServer
     */
    public function setExpName($expName)
    {
        $this->exp_name = $expName;

        return $this;
    }

    /**
     * Get exp_name
     *
     * @return string
     */
    public function getExpName()
    {
        return $this->exp_name;
    }

    /**
     * Set useDataset
     *
     * @param boolean $useDataset
     * @return LabServer
     */
    public function setUseDataset($useDataset)
    {
        $this->useDataset = $useDataset;

        return $this;
    }

    /**
     * Get useDataset
     *
     * @return boolean
     */
    public function getUseDataset()
    {
        return $this->useDataset;
    }

    /**
     * Set federate
     *
     * @param boolean $federate
     * @return LabServer
     */
    public function setFederate($federate)
    {
        $this->federate = $federate;

        return $this;
    }

    /**
     * Get federate
     *
     * @return boolean
     */
    public function getFederate()
    {
        return $this->federate;
    }

    /**
     * Set isaWsdlUrl
     *
     * @param string $isaWsdlUrl
     * @return LabServer
     */
    public function setIsaWsdlUrl($isaWsdlUrl)
    {
        $this->isaWsdlUrl = $isaWsdlUrl;

        return $this;
    }

    /**
     * Get isaWsdlUrl
     *
     * @return string
     */
    public function getIsaWsdlUrl()
    {
        return $this->isaWsdlUrl;
    }

    /**
     * Set isaIdentifier
     *
     * @param string $isaIdentifier
     * @return LabServer
     */
    public function setIsaIdentifier($isaIdentifier)
    {
        $this->isaIdentifier = $isaIdentifier;

        return $this;
    }

    /**
     * Get isaIdentifier
     *
     * @return string
     */
    public function getIsaIdentifier()
    {
        return $this->isaIdentifier;
    }

    /**
     * Set isaPasskeyToLabServer
     *
     * @param string $isaPasskeyToLabServer
     * @return LabServer
     */
    public function setIsaPasskeyToLabServer($isaPasskeyToLabServer)
    {
        $this->isaPasskeyToLabServer = $isaPasskeyToLabServer;

        return $this;
    }

    /**
     * Get isaPasskeyToLabServer
     *
     * @return string
     */
    public function getIsaPasskeyToLabServer()
    {
        return $this->isaPasskeyToLabServer;
    }
}