text:
import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';

import * as firestore from '@firebase/firestore-types';
import { expect } from 'chai';

import { fail } from '../../../src/util/assert';
import { Code } from '../../../src/util/error';
import { query } from '../../util/api_helpers';
import { Deferred } from '../../util/promise';
import { EventsAccumulator } from '../util/events_accumulator';
import firebase from '../util/firebase_export';
import {
  apiDescribe,
  withTestCollection,
  withTestDb,
  withTestDbs,
  withTestDoc,
  withTestDocAndInitialData
} from '../util/helpers';

chai.use(chaiAsPromised);

const Timestamp = firebase.firestore!.Timestamp;
const FieldValue = firebase.firestore!.FieldValue;

apiDescribe('Database', persistence => {
  it('can set a document', () => {
    return withTestDoc(persistence, docRef => {
      return docRef.set({
        desc: 'Stuff related to Firestore project...',
        owner: {
          name: 'Jonny',
          title: 'scallywag'
        }
      });
    });
  });

  it('doc() will auto generate an ID', () => {
    return withTestDb(persistence, async db => {
      const ref = db.collection('foo').doc();
      // Auto IDs are 20 characters long
      expect(ref.id.length).to.equal(20);
    });
  });

  it('can delete a document', () => {
    return withTestDoc(persistence, docRef => {
      return docRef
        .set({ foo: 'bar' })
        .then(() => {
          return docRef.get();
        })
        .then(doc => {
          expect(doc.data()).to.deep.equal({ foo: 'bar' });
          return docRef.delete();
        })
        .then(() => {
          return docRef.get();
        })
        .then(doc => {
          expect(doc.exists).to.equal(false);
        });
    });
  });

  it('can update existing document', () => {
    return withTestDoc(persistence, doc => {
      const initialData = {
        desc: 'Description',
        owner: { name: 'Jonny', email: 'abc@xyz.com' }
      };
      const updateData = {
        desc: 'NewDescription',
        'owner.email': 'new@xyz.com'
      };
      const finalData = {
        desc: 'NewDescription',
        owner: { name: 'Jonny', email: 'new@xyz.com' }
      };
      return doc
        .set(initialData)
        .then(() => doc.update(updateData))
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.be.ok;
          expect(docSnapshot.data()).to.deep.equal(finalData);
        });
    });
  });

  it('can retrieve document that does not exist', () => {
    return withTestDoc(persistence, doc => {
      return doc.get().then(snapshot => {
        expect(snapshot.exists).to.equal(false);
        expect(snapshot.data()).to.equal(undefined);
        expect(snapshot.get('foo')).to.equal(undefined);
      });
    });
  });

  (persistence ? it : it.skip)('can update an unknown document', () => {
    return withTestDbs(persistence, 2, async ([reader, writer]) => {
      const writerRef = writer.collection('collection').doc();
      const readerRef = reader.collection('collection').doc(writerRef.id);
      await writerRef.set({ a: 'a' });
      await readerRef.update({ b: 'b' });
      await writerRef
        .get({ source: 'cache' })
        .then(doc => expect(doc.exists).to.be.true);
      await readerRef
        .get({ source: 'cache' })
        .then(
          () => fail('Expected cache miss'),
          err => expect(err.code).to.be.equal(Code.UNAVAILABLE)
        );
      await writerRef
        .get()
        .then(doc => expect(doc.data()).to.deep.equal({ a: 'a', b: 'b' }));
      await readerRef
        .get()
        .then(doc => expect(doc.data()).to.deep.equal({ a: 'a', b: 'b' }));
    });
  });

  it('can merge data with an existing document using set', () => {
    return withTestDoc(persistence, doc => {
      const initialData = {
        desc: 'description',
        'owner.data': { name: 'Jonny', email: 'abc@xyz.com' }
      };
      const mergeData = {
        updated: true,
        'owner.data': { name: 'Sebastian' }
      };
      const finalData = {
        updated: true,
        desc: 'description',
        'owner.data': { name: 'Sebastian', email: 'abc@xyz.com' }
      };
      return doc
        .set(initialData)
        .then(() => doc.set(mergeData, { merge: true }))
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.be.ok;
          expect(docSnapshot.data()).to.deep.equal(finalData);
        });
    });
  });

  it('can merge server timestamps', () => {
    return withTestDoc(persistence, doc => {
      const initialData = {
        updated: false
      };
      const mergeData = {
        time: FieldValue.serverTimestamp(),
        nested: { time: FieldValue.serverTimestamp() }
      };
      return doc
        .set(initialData)
        .then(() => doc.set(mergeData, { merge: true }))
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.be.ok;
          expect(docSnapshot.get('updated')).to.be.false;
          expect(docSnapshot.get('time')).to.be.an.instanceof(Timestamp);
          expect(docSnapshot.get('nested.time')).to.be.an.instanceof(Timestamp);
        });
    });
  });

  it('can merge empty object', async () => {
    await withTestDoc(persistence, async doc => {
      const accumulator = new EventsAccumulator<firestore.DocumentSnapshot>();
      const unsubscribe = doc.onSnapshot(accumulator.storeEvent);
      await accumulator
        .awaitEvent()
        .then(() => doc.set({}))
        .then(() => accumulator.awaitEvent())
        .then(docSnapshot => expect(docSnapshot.data()).to.be.deep.equal({}))
        .then(() => doc.set({ a: {} }, { mergeFields: ['a'] }))
        .then(() => accumulator.awaitEvent())
        .then(docSnapshot =>
          expect(docSnapshot.data()).to.be.deep.equal({ a: {} })
        )
        .then(() => doc.set({ b: {} }, { merge: true }))
        .then(() => accumulator.awaitEvent())
        .then(docSnapshot =>
          expect(docSnapshot.data()).to.be.deep.equal({ a: {}, b: {} })
        )
        .then(() => doc.get({ source: 'server' }))
        .then(docSnapshot => {
          expect(docSnapshot.data()).to.be.deep.equal({ a: {}, b: {} });
        });

      unsubscribe();
    });
  });

  it('can delete field using merge', () => {
    return withTestDoc(persistence, doc => {
      const initialData = {
        untouched: true,
        foo: 'bar',
        nested: { untouched: true, foo: 'bar' }
      };
      const mergeData = {
        foo: FieldValue.delete(),
        nested: { foo: FieldValue.delete() }
      };
      const finalData = {
        untouched: true,
        nested: { untouched: true }
      };
      return doc
        .set(initialData)
        .then(() => doc.set(mergeData, { merge: true }))
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.be.ok;
          expect(docSnapshot.data()).to.deep.equal(finalData);
        });
    });
  });

  it('can delete field using mergeFields', () => {
    return withTestDoc(persistence, doc => {
      const initialData = {
        untouched: true,
        foo: 'bar',
        inner: { removed: true, foo: 'bar' },
        nested: { untouched: true, foo: 'bar' }
      };
      const mergeData = {
        foo: FieldValue.delete(),
        inner: { foo: FieldValue.delete() },
        nested: {
          untouched: FieldValue.delete(),
          foo: FieldValue.delete()
        }
      };
      const finalData = {
        untouched: true,
        inner: {},
        nested: { untouched: true }
      };
      return doc
        .set(initialData)
        .then(() =>
          doc.set(mergeData, { mergeFields: ['foo', 'inner', 'nested.foo'] })
        )
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.be.ok;
          expect(docSnapshot.data()).to.deep.equal(finalData);
        });
    });
  });

  it('can set server timestamps using mergeFields', () => {
    return withTestDoc(persistence, doc => {
      const initialData = {
        untouched: true,
        foo: 'bar',
        nested: { untouched: true, foo: 'bar' }
      };
      const mergeData = {
        foo: FieldValue.serverTimestamp(),
        inner: { foo: FieldValue.serverTimestamp() },
        nested: { foo: FieldValue.serverTimestamp() }
      };
      return doc
        .set(initialData)
        .then(() =>
          doc.set(mergeData, { mergeFields: ['foo', 'inner', 'nested.foo'] })
        )
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.be.ok;
          expect(docSnapshot.get('foo')).to.be.instanceof(Timestamp);
          expect(docSnapshot.get('inner.foo')).to.be.instanceof(Timestamp);
          expect(docSnapshot.get('nested.foo')).to.be.instanceof(Timestamp);
        });
    });
  });

  it('can replace an array by merging using set', () => {
    return withTestDoc(persistence, doc => {
      const initialData = {
        untouched: true,
        data: 'old',
        topLevel: ['old', 'old'],
        mapInArray: [{ data: 'old' }]
      };
      const mergeData = {
        data: 'new',
        topLevel: ['new'],
        mapInArray: [{ data: 'new' }]
      };
      const finalData = {
        untouched: true,
        data: 'new',
        topLevel: ['new'],
        mapInArray: [{ data: 'new' }]
      };
      return doc
        .set(initialData)
        .then(() => doc.set(mergeData, { merge: true }))
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.be.ok;
          expect(docSnapshot.data()).to.deep.equal(finalData);
        });
    });
  });

  it("can't specify a field mask for a missing field using set", () => {
    return withTestDoc(persistence, async docRef => {
      expect(() => {
        docRef.set(
          { desc: 'NewDescription' },
          { mergeFields: ['desc', 'owner'] }
        );
      }).to.throw(
        "Field 'owner' is specified in your field mask but missing from your input data."
      );
    });
  });

  it('can set a subset of fields using a field mask', () => {
    const initialData = {
      desc: 'Description',
      owner: { name: 'Jonny', email: 'abc@xyz.com' }
    };
    const finalData = { desc: 'Description', owner: 'Sebastian' };
    return withTestDocAndInitialData(persistence, initialData, async docRef => {
      await docRef.set(
        { desc: 'NewDescription', owner: 'Sebastian' },
        { mergeFields: ['owner'] }
      );
      const result = await docRef.get();
      expect(result.data()).to.deep.equal(finalData);
    });
  });

  it("doesn't apply field delete outside of mask", () => {
    const initialData = {
      desc: 'Description',
      owner: { name: 'Jonny', email: 'abc@xyz.com' }
    };
    const finalData = { desc: 'Description', owner: 'Sebastian' };
    return withTestDocAndInitialData(persistence, initialData, async docRef => {
      await docRef.set(
        { desc: FieldValue.delete(), owner: 'Sebastian' },
        { mergeFields: ['owner'] }
      );
      const result = await docRef.get();
      expect(result.data()).to.deep.equal(finalData);
    });
  });

  it("doesn't apply field transform outside of mask", () => {
    const initialData = {
      desc: 'Description',
      owner: { name: 'Jonny', email: 'abc@xyz.com' }
    };
    const finalData = { desc: 'Description', owner: 'Sebastian' };
    return withTestDocAndInitialData(persistence, initialData, async docRef => {
      await docRef.set(
        {
          desc: FieldValue.serverTimestamp(),
          owner: 'Sebastian'
        },
        { mergeFields: ['owner'] }
      );
      const result = await docRef.get();
      expect(result.data()).to.deep.equal(finalData);
    });
  });

  it('can set an empty field mask', () => {
    const initialData = {
      desc: 'Description',
      owner: { name: 'Jonny', email: 'abc@xyz.com' }
    };
    const finalData = initialData;
    return withTestDocAndInitialData(persistence, initialData, async docRef => {
      await docRef.set(
        { desc: 'NewDescription', owner: 'Sebastian' },
        { mergeFields: [] }
      );
      const result = await docRef.get();
      expect(result.data()).to.deep.equal(finalData);
    });
  });

  it('can specify fields multiple times in a field mask', () => {
    const initialData = {
      desc: 'Description',
      owner: { name: 'Jonny', email: 'abc@xyz.com' }
    };
    const finalData = {
      desc: 'Description',
      owner: { name: 'Sebastian', email: 'new@xyz.com' }
    };
    return withTestDocAndInitialData(persistence, initialData, async docRef => {
      await docRef.set(
        {
          desc: 'NewDescription',
          owner: { name: 'Sebastian', email: 'new@xyz.com' }
        },
        { mergeFields: ['owner.name', 'owner', 'owner'] }
      );
      const result = await docRef.get();
      expect(result.data()).to.deep.equal(finalData);
    });
  });

  it('cannot update nonexistent document', () => {
    return withTestDoc(persistence, doc => {
      return doc
        .update({ owner: 'abc' })
        .then(
          () => Promise.reject('update should have failed.'),
          (err: firestore.FirestoreError) => {
            expect(err.message).to.exist;
            // TODO: Change this to just match "no document to update" once the
            // backend response is consistent.
            expect(err.message).to.match(/no (document|entity) to update/i);
            expect(err.code).to.equal('not-found');
          }
        )
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.equal(false);
        });
    });
  });

  it('can delete a field with an update', () => {
    return withTestDoc(persistence, doc => {
      const initialData = {
        desc: 'Description',
        owner: { name: 'Jonny', email: 'abc@xyz.com' }
      };
      const updateData = {
        'owner.email': FieldValue.delete()
      };
      const finalData = {
        desc: 'Description',
        owner: { name: 'Jonny' }
      };
      return doc
        .set(initialData)
        .then(() => doc.update(updateData))
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.be.ok;
          expect(docSnapshot.data()).to.deep.equal(finalData);
        });
    });
  });

  it('can update nested fields', () => {
    const FieldPath = firebase.firestore!.FieldPath;

    return withTestDoc(persistence, doc => {
      const initialData = {
        desc: 'Description',
        owner: { name: 'Jonny' },
        'is.admin': false
      };
      const finalData = {
        desc: 'Description',
        owner: { name: 'Sebastian' },
        'is.admin': true
      };
      return doc
        .set(initialData)
        .then(() =>
          doc.update('owner.name', 'Sebastian', new FieldPath('is.admin'), true)
        )
        .then(() => doc.get())
        .then(docSnapshot => {
          expect(docSnapshot.exists).to.be.ok;
          expect(docSnapshot.data()).to.deep.equal(finalData);
        });
    });
  });

  describe('documents: ', () => {
    const invalidDocValues = [undefined, null, 0, 'foo', ['a'], new Date()];
    for (const val of invalidDocValues) {
      it('set/update should reject: ' + val, () => {
        return withTestDoc(persistence, async doc => {
          // tslint:disable-next-line:no-any Intentionally passing bad types.
          expect(() => doc.set(val as any)).to.throw();
          // tslint:disable-next-line:no-any Intentionally passing bad types.
          expect(() => doc.update(val as any)).to.throw();
        });
      });
    }
  });

  it('CollectionRef.add() resolves with resulting DocumentRef.', () => {
    return withTestCollection(persistence, {}, coll => {
      return coll
        .add({ foo: 1 })
        .then(docRef => docRef.get())
        .then(docSnap => {
          expect(docSnap.data()).to.deep.equal({ foo: 1 });
        });
    });
  });

  apiDescribe('Queries are validated client-side', persistence => {
    // NOTE: Failure cases are validated in validation_test.ts

    it('same inequality fields works', () => {
      return withTestCollection(persistence, {}, async coll => {
        expect(() =>
          coll.where('x', '>=', 32).where('x', '<=', 'cat')
        ).not.to.throw();
      });
    });

    it('inequality and equality on different fields works', () => {
      return withTestCollection(persistence, {}, async coll => {
        expect(() =>
          coll.where('x', '>=', 32).where('y', '==', 'cat')
        ).not.to.throw();
      });
    });

    it('inequality and array-contains on different fields works', () => {
      return withTestCollection(persistence, {}, async coll => {
        expect(() =>
          coll.where('x', '>=', 32).where('y', 'array-contains', 'cat')
        ).not.to.throw();
      });
    });

    it('inequality same as orderBy works.', () => {
      return withTestCollection(persistence, {}, async coll => {
        expect(() => coll.where('x', '>', 32).orderBy('x')).not.to.throw();
        expect(() => coll.orderBy('x').where('x', '>', 32)).not.to.throw();
      });
    });

    it('inequality same as first orderBy works.', () => {
      return withTestCollection(persistence, {}, async coll => {
        expect(() =>
          coll
            .where('x', '>', 32)
            .orderBy('x')
            .orderBy('y')
        ).not.to.throw();
        expect(() =>
          coll
            .orderBy('x')
            .where('x', '>', 32)
            .orderBy('y')
        ).not.to.throw();
      });
    });

    it('equality different than orderBy works', () => {
      return withTestCollection(persistence, {}, async coll => {
        expect(() => coll.orderBy('x').where('y', '==', 'cat')).not.to.throw();
      });
    });

    it('array-contains different than orderBy works', () => {
      return withTestCollection(persistence, {}, async coll => {
        expect(() =>
          coll.orderBy('x').where('y', 'array-contains', 'cat')
        ).not.to.throw();
      });
    });
  });

  it('DocumentSnapshot events for non existent document', () => {
    return withTestCollection(persistence, {}, col => {
      const doc = col.doc();
      const storeEvent = new EventsAccumulator<firestore.DocumentSnapshot>();
      doc.onSnapshot(storeEvent.storeEvent);
      return storeEvent.awaitEvent().then(snap => {
        expect(snap.exists).to.be.false;
        expect(snap.data()).to.equal(undefined);
        return storeEvent.assertNoAdditionalEvents();
      });
    });
  });

  it('DocumentSnapshot events for add data to document', () => {
    return withTestCollection(persistence, {}, col => {
      const doc = col.doc();
      const storeEvent = new EventsAccumulator<firestore.DocumentSnapshot>();
      doc.onSnapshot({ includeMetadataChanges: true }, storeEvent.storeEvent);
      return storeEvent
        .awaitEvent()
        .then(snap => {
          expect(snap.exists).to.be.false;
          expect(snap.data()).to.equal(undefined);
        })
        .then(() => doc.set({ a: 1 }))
        .then(() => storeEvent.awaitEvent())
        .then(snap => {
          expect(snap.exists).to.be.true;
          expect(snap.data()).to.deep.equal({ a: 1 });
          expect(snap.metadata.hasPendingWrites).to.be.true;
        })
        .then(() => storeEvent.awaitEvent())
        .then(snap => {
          expect(snap.exists).to.be.true;
          expect(snap.data()).to.deep.equal({ a: 1 });
          expect(snap.metadata.hasPendingWrites).to.be.false;
        })
        .then(() => storeEvent.assertNoAdditionalEvents());
    });
  });

  it('DocumentSnapshot events for change data in document', () => {
    const initialData = { a: 1 };
    const changedData = { b: 2 };

    return withTestCollection(persistence, { key1: initialData }, col => {
      const doc = col.doc('key1');
      const storeEvent = new EventsAccumulator<firestore.DocumentSnapshot>();
      doc.onSnapshot({ includeMetadataChanges: true }, storeEvent.storeEvent);
      return storeEvent
        .awaitEvent()
        .then(snap => {
          expect(snap.data()).to.deep.equal(initialData);
          expect(snap.metadata.hasPendingWrites).to.be.false;
        })
        .then(() => doc.set(changedData))
        .then(() => storeEvent.awaitEvent())
        .then(snap => {
          expect(snap.data()).to.deep.equal(changedData);
          expect(snap.metadata.hasPendingWrites).to.be.true;
        })
        .then(() => storeEvent.awaitEvent())
        .then(snap => {
          expect(snap.data()).to.deep.equal(changedData);
          expect(snap.metadata.hasPendingWrites).to.be.false;
        })
        .then(() => storeEvent.assertNoAdditionalEvents());
    });
  });

  it('DocumentSnapshot events for delete data in document', () => {
    const initialData = { a: 1 };

    return withTestCollection(persistence, { key1: initialData }, col => {
      const doc = col.doc('key1');
      const storeEvent = new EventsAccumulator<firestore.DocumentSnapshot>();
      doc.onSnapshot({ includeMetadataChanges: true }, storeEvent.storeEvent);
      return storeEvent
        .awaitEvent()
        .then(snap => {
          expect(snap.exists).to.be.true;
          expect(snap.data()).to.deep.equal(initialData);
          expect(snap.metadata.hasPendingWrites).to.be.false;
        })
        .then(() => doc.delete())
        .then(() => storeEvent.awaitEvent())
        .then(snap => {
          expect(snap.exists).to.be.false;
          expect(snap.data()).to.equal(undefined);
          expect(snap.metadata.hasPendingWrites).to.be.false;
        })
        .then(() => storeEvent.assertNoAdditionalEvents());
    });
  });

  it('Listen can be called multiple times', () => {
    return withTestCollection(persistence, {}, coll => {
      const doc = coll.doc();
      const deferred1 = new Deferred<void>();
      const deferred2 = new Deferred<void>();
      doc.set({ foo: 'bar' }).then(() => {
        doc.onSnapshot(snap => {
          deferred1.resolve();
          doc.onSnapshot(snap => {
            deferred2.resolve();
          });
        });
      });
      return Promise.all([deferred1.promise, deferred2.promise]).then(() => {});
    });
  });

  it('Metadata only changes are not fired when no options provided', () => {
    return withTestDoc(persistence, docRef => {
      const secondUpdateFound = new Deferred();
      let count = 0;
      const unlisten = docRef.onSnapshot(doc => {
        if (doc) {
          count++;
          if (count === 1) {
            expect(doc.data()).to.deep.equal({ a: 1 });
          } else {
            expect(doc.data()).to.deep.equal({ b: 1 });
            secondUpdateFound.resolve();
          }
        }
      });

      docRef.set({ a: 1 }).then(() => {
        docRef.set({ b: 1 });
      });
      return secondUpdateFound.promise.then(() => {
        unlisten();
      });
    });
  });

  // TODO(mikelehen): We need a way to create a query that will pass
  // client-side validation but fail remotely.  May need to wait until we
  // have security rules support or something?
  // tslint:disable-next-line:ban
  describe.skip('Listens are rejected remotely:', () => {
    const queryForRejection = query('foo');

    it('will reject listens', () => {
      const deferred = new Deferred();
      queryForRejection.onSnapshot(
        () => {},
        (err: Error) => {
          expect(err.name).to.exist;
          expect(err.message).to.exist;
          deferred.resolve();
        }
      );
      return deferred.promise;
    });

    it('will reject same listens twice in a row', () => {
      const deferred = new Deferred();
      queryForRejection.onSnapshot(
        () => {},
        (err: Error) => {
          expect(err.name).to.exist;
          expect(err.message).to.exist;
          queryForRejection.onSnapshot(
            () => {},
            (err2: Error) => {
              expect(err2.name).to.exist;
              expect(err2.message).to.exist;
              deferred.resolve();
            }
          );
        }
      );
      return deferred.promise;
    });

    it('will reject gets', () => {
      return queryForRejection.get().then(
        () => {
          throw new Error('Promise resolved even though error was expected.');
        },
        err => {
          expect(err.name).to.exist;
          expect(err.message).to.exist;
        }
      );
    });

    it('will reject gets twice in a row', () => {
      return queryForRejection
        .get()
        .then(
          () => {
            throw new Error('Promise resolved even though error was expected.');
          },
          err => {
            expect(err.name).to.exist;
            expect(err.message).to.exist;
          }
        )
        .then(() => queryForRejection.get())
        .then(
          () => {
            throw new Error('Promise resolved even though error was expected.');
          },
          err => {
            expect(err.name).to.exist;
            expect(err.message).to.exist;
          }
        );
    });
  });

  it('exposes "firestore" on document references.', () => {
    return withTestDb(persistence, async db => {
      expect(db.doc('foo/bar').firestore).to.equal(db);
    });
  });

  it('exposes "firestore" on query references.', () => {
    return withTestDb(persistence, async db => {
      expect(db.collection('foo').limit(5).firestore).to.equal(db);
    });
  });

  it('can compare DocumentReference instances with isEqual().', () => {
    return withTestDb(persistence, firestore => {
      return withTestDb(persistence, async otherFirestore => {
        const docRef = firestore.doc('foo/bar');
        expect(docRef.isEqual(firestore.doc('foo/bar'))).to.be.true;
        expect(docRef.collection('baz').parent!.isEqual(docRef)).to.be.true;

        expect(firestore.doc('foo/BAR').isEqual(docRef)).to.be.false;

        expect(otherFirestore.doc('foo/bar').isEqual(docRef)).to.be.false;
      });
    });
  });

  it('can compare Query instances with isEqual().', () => {
    return withTestDb(persistence, firestore => {
      return withTestDb(persistence, async otherFirestore => {
        const query = firestore
          .collection('foo')
          .orderBy('bar')
          .where('baz', '==', 42);
        const query2 = firestore
          .collection('foo')
          .orderBy('bar')
          .where('baz', '==', 42);
        expect(query.isEqual(query2)).to.be.true;

        const query3 = firestore
          .collection('foo')
          .orderBy('BAR')
          .where('baz', '==', 42);
        expect(query.isEqual(query3)).to.be.false;

        const query4 = otherFirestore
          .collection('foo')
          .orderBy('bar')
          .where('baz', '==', 42);
        expect(query4.isEqual(query)).to.be.false;
      });
    });
  });

  it('can traverse collections and documents.', () => {
    return withTestDb(persistence, async db => {
      const expected = 'a/b/c/d';
      // doc path from root Firestore.
      expect(db.doc('a/b/c/d').path).to.deep.equal(expected);
      // collection path from root Firestore.
      expect(db.collection('a/b/c').doc('d').path).to.deep.equal(expected);
      // doc path from CollectionReference.
      expect(db.collection('a').doc('b/c/d').path).to.deep.equal(expected);
      // collection path from DocumentReference.
      expect(db.doc('a/b').collection('c/d/e').path).to.deep.equal(
        expected + '/e'
      );
    });
  });

  it('can traverse collection and document parents.', () => {
    return withTestDb(persistence, async db => {
      let collection = db.collection('a/b/c');
      expect(collection.path).to.deep.equal('a/b/c');

      const doc = collection.parent!;
      expect(doc.path).to.deep.equal('a/b');

      collection = doc.parent;
      expect(collection.path).to.equal('a');

      const nullDoc = collection.parent;
      expect(nullDoc).to.equal(null);
    });
  });

  it('can queue writes while offline', () => {
    return withTestDoc(persistence, docRef => {
      const firestore = docRef.firestore;

      return firestore
        .disableNetwork()
        .then(() => {
          return Promise.all([
            docRef.set({ foo: 'bar' }),
            firestore.enableNetwork()
          ]);
        })
        .then(() => docRef.get())
        .then(doc => {
          expect(doc.data()).to.deep.equal({ foo: 'bar' });
        });
    });
  });

  it('can get documents while offline', async () => {
    await withTestDoc(persistence, async docRef => {
      const firestore = docRef.firestore;

      await firestore.disableNetwork();
      await expect(docRef.get()).to.eventually.be.rejectedWith(
        'Failed to get document because the client is offline.'
      );

      const writePromise = docRef.set({ foo: 'bar' });
      const doc = await docRef.get();
      expect(doc.metadata.fromCache).to.be.true;

      await firestore.enableNetwork();
      await writePromise;

      const doc2 = await docRef.get();
      expect(doc2.metadata.fromCache).to.be.false;
      expect(doc2.data()).to.deep.equal({ foo: 'bar' });
    });
  });

  it('can enable and disable networking', () => {
    return withTestDb(persistence, async db => {
      // There's not currently a way to check if networking is in fact disabled,
      // so for now just test that the method is well-behaved and doesn't throw.
      await db.enableNetwork();
      await db.enableNetwork();
      await db.disableNetwork();
      await db.disableNetwork();
      await db.enableNetwork();
    });
  });
});


text:
namespace page_load_metrics {

namespace {

// Simple PageLoadMetricsObserver that copies observed PageLoadTimings into the
// provided std::vector, so they can be analyzed by unit tests.
class TestPageLoadMetricsObserver : public PageLoadMetricsObserver {
 public:
  TestPageLoadMetricsObserver(
      std::vector<mojom::PageLoadTimingPtr>* updated_timings,
      std::vector<mojom::PageLoadTimingPtr>* updated_subframe_timings,
      std::vector<mojom::PageLoadTimingPtr>* complete_timings,
      std::vector<mojom::CpuTimingPtr>* updated_cpu_timings,
      std::vector<ExtraRequestCompleteInfo>* loaded_resources,
      std::vector<GURL>* observed_committed_urls,
      std::vector<GURL>* observed_aborted_urls,
      std::vector<blink::UseCounterFeature>* observed_features,
      absl::optional<bool>* is_first_navigation_in_web_contents,
      int* count_on_enter_back_forward_cache)
      : updated_timings_(updated_timings),
        updated_subframe_timings_(updated_subframe_timings),
        complete_timings_(complete_timings),
        updated_cpu_timings_(updated_cpu_timings),
        loaded_resources_(loaded_resources),
        observed_features_(observed_features),
        observed_committed_urls_(observed_committed_urls),
        observed_aborted_urls_(observed_aborted_urls),
        is_first_navigation_in_web_contents_(
            is_first_navigation_in_web_contents),
        count_on_enter_back_forward_cache_(count_on_enter_back_forward_cache) {}

  ObservePolicy OnStart(content::NavigationHandle* navigation_handle,
                        const GURL& currently_committed_url,
                        bool started_in_foreground) override {
    observed_committed_urls_->push_back(currently_committed_url);
    *is_first_navigation_in_web_contents_ =
        GetDelegate().IsFirstNavigationInWebContents();
    return CONTINUE_OBSERVING;
  }

  void OnTimingUpdate(content::RenderFrameHost* subframe_rfh,
                      const mojom::PageLoadTiming& timing) override {
    if (subframe_rfh) {
      DCHECK(subframe_rfh->GetParent());
      updated_subframe_timings_->push_back(timing.Clone());
    } else {
      updated_timings_->push_back(timing.Clone());
    }
  }

  void OnCpuTimingUpdate(content::RenderFrameHost* subframe_rfh,
                         const mojom::CpuTiming& timing) override {
    updated_cpu_timings_->push_back(timing.Clone());
  }

  void OnComplete(const mojom::PageLoadTiming& timing) override {
    complete_timings_->push_back(timing.Clone());
  }

  ObservePolicy FlushMetricsOnAppEnterBackground(
      const mojom::PageLoadTiming& timing) override {
    return STOP_OBSERVING;
  }

  void OnLoadedResource(
      const ExtraRequestCompleteInfo& extra_request_complete_info) override {
    loaded_resources_->emplace_back(extra_request_complete_info);
  }

  void OnFeaturesUsageObserved(
      content::RenderFrameHost* rfh,
      const std::vector<blink::UseCounterFeature>& features) override {
    observed_features_->insert(observed_features_->end(), features.begin(),
                               features.end());
  }

  void OnDidInternalNavigationAbort(
      content::NavigationHandle* navigation_handle) override {
    observed_aborted_urls_->push_back(navigation_handle->GetURL());
  }

  ObservePolicy OnEnterBackForwardCache(
      const mojom::PageLoadTiming& timing) override {
    (*count_on_enter_back_forward_cache_)++;
    return PageLoadMetricsObserver::OnEnterBackForwardCache(timing);
  }

 private:
  const raw_ptr<std::vector<mojom::PageLoadTimingPtr>> updated_timings_;
  const raw_ptr<std::vector<mojom::PageLoadTimingPtr>>
      updated_subframe_timings_;
  const raw_ptr<std::vector<mojom::PageLoadTimingPtr>> complete_timings_;
  const raw_ptr<std::vector<mojom::CpuTimingPtr>> updated_cpu_timings_;
  const raw_ptr<std::vector<ExtraRequestCompleteInfo>> loaded_resources_;
  const raw_ptr<std::vector<blink::UseCounterFeature>> observed_features_;
  const raw_ptr<std::vector<GURL>> observed_committed_urls_;
  const raw_ptr<std::vector<GURL>> observed_aborted_urls_;
  raw_ptr<absl::optional<bool>> is_first_navigation_in_web_contents_;
  const raw_ptr<int> count_on_enter_back_forward_cache_;
};

// Test PageLoadMetricsObserver that stops observing page loads with certain
// substrings in the URL.
class FilteringPageLoadMetricsObserver : public PageLoadMetricsObserver {
 public:
  explicit FilteringPageLoadMetricsObserver(
      std::vector<GURL>* completed_filtered_urls)
      : completed_filtered_urls_(completed_filtered_urls) {}

  ObservePolicy OnStart(content::NavigationHandle* handle,
                        const GURL& currently_committed_url,
                        bool started_in_foreground) override {
    const bool should_ignore =
        handle->GetURL().spec().find("ignore-on-start") != std::string::npos;
    return should_ignore ? STOP_OBSERVING : CONTINUE_OBSERVING;
  }

  ObservePolicy OnCommit(content::NavigationHandle* handle,
                         ukm::SourceId source_id) override {
    const bool should_ignore =
        handle->GetURL().spec().find("ignore-on-commit") != std::string::npos;
    return should_ignore ? STOP_OBSERVING : CONTINUE_OBSERVING;
  }

  void OnComplete(const mojom::PageLoadTiming& timing) override {
    completed_filtered_urls_->push_back(GetDelegate().GetUrl());
  }

 private:
  const raw_ptr<std::vector<GURL>> completed_filtered_urls_;
};

}  // namespace

TestMetricsWebContentsObserverEmbedder::
    TestMetricsWebContentsObserverEmbedder() = default;

TestMetricsWebContentsObserverEmbedder::
    ~TestMetricsWebContentsObserverEmbedder() = default;

bool TestMetricsWebContentsObserverEmbedder::IsNewTabPageUrl(const GURL& url) {
  return is_ntp_;
}

void TestMetricsWebContentsObserverEmbedder::RegisterObservers(
    PageLoadTracker* tracker) {
  tracker->AddObserver(std::make_unique<TestPageLoadMetricsObserver>(
      &updated_timings_, &updated_subframe_timings_, &complete_timings_,
      &updated_cpu_timings_, &loaded_resources_, &observed_committed_urls_,
      &observed_aborted_urls_, &observed_features_,
      &is_first_navigation_in_web_contents_,
      &count_on_enter_back_forward_cache_));
  tracker->AddObserver(std::make_unique<FilteringPageLoadMetricsObserver>(
      &completed_filtered_urls_));
}

std::unique_ptr<base::OneShotTimer>
TestMetricsWebContentsObserverEmbedder::CreateTimer() {
  auto timer = std::make_unique<test::WeakMockTimer>();
  SetMockTimer(timer->AsWeakPtr());
  return std::move(timer);
}

bool TestMetricsWebContentsObserverEmbedder::IsNoStatePrefetch(
    content::WebContents* web_contents) {
  return false;
}

bool TestMetricsWebContentsObserverEmbedder::IsExtensionUrl(const GURL& url) {
  return false;
}

bool TestMetricsWebContentsObserverEmbedder::IsSidePanel(
    content::WebContents* web_contents) {
  return false;
}

PageLoadMetricsMemoryTracker*
TestMetricsWebContentsObserverEmbedder::GetMemoryTrackerForBrowserContext(
    content::BrowserContext* browser_context) {
  return nullptr;
}

}  // namespace page_load_metrics

redpajama_set_name: RedPajamaGithub


text:
package org.apache.eagle.app.messaging;

import backtype.storm.Testing;
import backtype.storm.task.IOutputCollector;
import backtype.storm.task.OutputCollector;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import com.typesafe.config.Config;
import org.apache.eagle.app.environment.builder.MetricDescriptor;
import org.apache.eagle.app.utils.StreamConvertHelper;
import org.apache.eagle.log.entity.GenericMetricEntity;
import org.apache.eagle.log.entity.GenericServiceAPIResponseEntity;
import org.apache.eagle.service.client.impl.EagleServiceClientImpl;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.lang.reflect.Field;
import java.util.*;

import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

@RunWith(PowerMockRunner.class)
@PrepareForTest( {MetricStreamPersist.class})
public class MetricStreamPersistTest {

    @Test
    public void testStructuredMetricMapper() throws Exception {
        MetricDescriptor metricDefinition = MetricDescriptor
            .metricGroupByField("group")
            .siteAs("siteId")
            .namedByField("metric")
            .eventTimeByField("timestamp")
            .dimensionFields("host", "component", "site")
            .granularity(Calendar.MINUTE)
            .valueField("value");
        Config config = mock(Config.class);
        MetricStreamPersist metricStreamPersist = new MetricStreamPersist(metricDefinition, config);
        Field mapperField = metricStreamPersist.getClass().getDeclaredField("mapper");
        mapperField.setAccessible(true);

        Map event = new HashMap();
        event.put("timestamp", 1482106479564L);
        event.put("metric", "hadoop.memory.heapmemoryusage.used");
        event.put("component", "hbasemaster");
        event.put("site", "sandbox");
        event.put("value", 14460904.0);
        event.put("host", "xxx-xxx.int.xxx.com");

        Tuple tuple = Testing.testTuple(new Values("metric", event));
        MetricStreamPersist.MetricMapper mapper = (MetricStreamPersist.MetricMapper) mapperField.get(metricStreamPersist);

        GenericMetricEntity metricEntity = mapper.map(StreamConvertHelper.tupleToEvent(tuple).f1());

        Assert.assertEquals("prefix:hadoop.memory.heapmemoryusage.used, timestamp:1482106440000, humanReadableDate:2016-12-19 00:14:00,000, tags: component=hbasemaster,site=sandbox,host=xxx-xxx.int.xxx.com,, encodedRowkey:null", metricEntity.toString());
    }

    @Test
    public void testMetricStreamPersist() throws Exception {
        List<String> result = new ArrayList<>();
        OutputCollector collector = new OutputCollector(new IOutputCollector() {
            @Override
            public List<Integer> emit(String streamId, Collection<Tuple> anchors, List<Object> tuple) {
                result.add(String.valueOf(tuple.get(0)));
                return null;
            }

            @Override
            public void emitDirect(int taskId, String streamId, Collection<Tuple> anchors, List<Object> tuple) {

            }

            @Override
            public void ack(Tuple input) {

            }

            @Override
            public void fail(Tuple input) {

            }

            @Override
            public void reportError(Throwable error) {

            }
        });

        MetricDescriptor metricDefinition = MetricDescriptor
            .metricGroupByField("group")
            .siteAs("siteId")
            .namedByField("metric")
            .eventTimeByField("timestamp")
            .dimensionFields("host", "component", "site")
            .granularity(Calendar.MINUTE)
            .valueField("value");
        Config config = mock(Config.class);
        when(config.hasPath("service.batchSize")).thenReturn(false);

        GenericServiceAPIResponseEntity<String> response = mock(GenericServiceAPIResponseEntity.class);
        when(response.isSuccess()).thenReturn(true);

        EagleServiceClientImpl client = mock(EagleServiceClientImpl.class);
        PowerMockito.whenNew(EagleServiceClientImpl.class).withArguments(config).thenReturn(client);
        when(client.create(anyObject())).thenReturn(response);

        MetricStreamPersist metricStreamPersist = new MetricStreamPersist(metricDefinition, config);
        metricStreamPersist.prepare(null, null, collector);
        Map event = new HashMap();
        event.put("timestamp", 1482106479564L);
        event.put("metric", "hadoop.memory.heapmemoryusage.used");
        event.put("component", "hbasemaster");
        event.put("site", "sandbox");
        event.put("value", 14460904.0);
        event.put("host", "xxx-xxx.int.xxx.com");

        Tuple tuple = Testing.testTuple(new Values("metric", event));
        metricStreamPersist.execute(tuple);
        Assert.assertTrue(result.size() == 1);
        Assert.assertEquals("hadoop.memory.heapmemoryusage.used", result.get(0));
    }
}


text:
namespace platforms {
namespace darwinn {

#ifdef COMPILER_MSVC
enum { IS_COMPILER_MSVC = 1 };
#else
enum { IS_COMPILER_MSVC = 0 };
#endif

// Lower-level routine that takes a va_list and appends to a specified
// string. All other routines are just convenience wrappers around it.
void StringAppendV(std::string* dst, const char* format, va_list ap) {
  // First try with a small fixed size buffer
  static const int kSpaceLength = 1024;
  char space[kSpaceLength];

  // It's possible for methods that use a va_list to invalidate the data in it
  // upon use. The fix is to make a copy of the structure before using it and
  // use that copy instead.
  va_list backup_ap;
  va_copy(backup_ap, ap);
  int result = vsnprintf(space, kSpaceLength, format, backup_ap);
  va_end(backup_ap);

  if (result < kSpaceLength) {
    if (result >= 0) {
      // Normal case -- everything fit.
      dst->append(space, result);
      return;
    }

    if (IS_COMPILER_MSVC) {
      // Error or MSVC running out of space. MSVC 8.0 and higher can be asked
      // about space needed with the special idiom below:
      va_copy(backup_ap, ap);
      result = vsnprintf(nullptr, 0, format, backup_ap);
      va_end(backup_ap);
    }

    if (result < 0) {
      // Just an error.
      return;
    }
  }

  // Increase the buffer size to the size requested by vsnprintf, plus one for
  // the closing \0.
  int length = result + 1;
  char* buf = new char[length];

  // Restore the va_list before we use it again
  va_copy(backup_ap, ap);
  result = vsnprintf(buf, length, format, backup_ap);
  va_end(backup_ap);

  if (result >= 0 && result < length) {
    // It fit
    dst->append(buf, result);
  }
  delete[] buf;
}

std::string StringPrintf(const char* format, ...) {
  va_list ap;
  va_start(ap, format);
  std::string result;
  StringAppendV(&result, format, ap);
  va_end(ap);
  return result;
}

}  // namespace darwinn
}  // namespace platforms


text:
import * as React from 'react';

interface Props {
  label: string;
  name: string;
  value: boolean;
  onChange: any;
  className?: string;
}

export const CheckBoxComponent = (props: Props) => {
  return (
    <div className={`checkbox ${props.className}`}>
      <label htmlFor={props.name}>
        <input
          id={props.name}
          type="checkbox"
          name={props.name}
          checked={props.value}
          onChange={props.onChange}
        />
        {props.label}
      </label>
    </div>
  );
}


text:
<?php
/****************************************************************************/
/* ATutor																	*/
/****************************************************************************/
/* Copyright (c) 2002-2010                                                  */
/* Inclusive Design Institute                                               */
/* http://atutor.ca															*/
/*																			*/
/* This program is free software. You can redistribute it and/or			*/
/* modify it under the terms of the GNU General Public License				*/
/* as published by the Free Software Foundation.							*/
/****************************************************************************/
// $Id$

define('AT_INCLUDE_PATH', '../../../include/');
require(AT_INCLUDE_PATH.'vitals.inc.php');

authenticate(AT_PRIV_ADMIN);

if (isset($_POST['submit_yes'])) {
	require(AT_INCLUDE_PATH.'../mods/_core/backups/classes/Backup.class.php');
	$Backup = new Backup($db, $_SESSION['course_id']);
	$Backup->delete($_POST['backup_id']);
	$msg->addFeedback('ACTION_COMPLETED_SUCCESSFULLY');
	header('Location: index.php');
	exit;
}

else if (isset($_POST['submit_no'])) {
	$msg->addFeedback('CANCELLED');
	header('Location: index.php');
	exit;
}

require(AT_INCLUDE_PATH.'header.inc.php');

	$delete_backup = intval($_REQUEST['backup_id']);
	$sql = "SELECT * from %sbackups WHERE backup_id = '%s'";
	$rows_backups = queryDB($sql, array(TABLE_PREFIX, $delete_backup));

foreach($rows_backups as $row){
	$title = $row['file_name'];
}
	$index['backup_id'] = $_GET['backup_id'];
	$msg->addConfirm(array('DELETE', $title), $index);
	$msg->printConfirm();

require (AT_INCLUDE_PATH.'footer.inc.php');

?>


text:
=head1 NAME

B<simple_de_test.pl>

=head1 DESCRIPTION

Simple differential expression test. Gene expression data should be stored in two tables, one for each condition. These can be created by the script C<combine_replicates.pl>.

This script can perform a few flavours of t-test, Mann-Whitney test and Kolmogorov-Smirnov test. See option C<-test> for details.

Results are stored in a tab-delimited output file. Columns are:

  * gene name
  * log2 fold change
  * p-value
  * mean for first condition
  * mean for second condition

=cut

use strict;
use warnings;

use PDL;
use PDL::NiceSlice;
use PDL::Graphics::PLplot;

use Math::CDF qw(:all);

use GRNASeq;
use GetOpt;

use PLgraphs;
use Tools;
use HTMLTable;
use Stats;

$| = 1;

my $test = 't';
my $outfile;
my $randcond;
my $defsfile;
GetMyOptions(
  'test=s' => \$test,
  'outfile=s' => \$outfile,
  'randcond=s' => \$randcond,
  'defsfile=s' => \$defsfile
);

###############################################

warn "WARNING: KS test does not work properly for discrete data\n" if $test eq 'ks';

ReadDefs($defsfile);
my %data = GetNormalizedData(
  include=>$include,
  nonzero=>$nonzero,
  norm=>$norm,
  type=>$type,
  clean=>$clean,
  spclean=>$spclean,
  randrep=>$randrep,
  randrep2=>$randrep2,
  condition => $randcond
);

my @myconds = @conds;
if(defined $randrep2)
{
  die "Need -randcond for randrep2\n" unless defined $randcond;
  @myconds = ("$randcond.1", "$randcond.2");
}

my @genes;
my %g2i = ();
my $i = 0;
for my $c (@myconds)
{
  my ($d, $m, $s, $nrep, $ngen, $genes, $name, $sel) = @{$data{$c}};
  my %g = GenHash($genes, $sel);
  $g2i{$c} = \%g;
  @genes = @$genes if $i == 0;
  $i++
}

my ($cond1, $cond2) = @myconds;
my $d1 = $data{$cond1}[0];
my $d2 = $data{$cond2}[0];

my $cl = ($clean) ? '_clean' : '';
my $nm = $norm;
my $rr = ($randrep) ? "_rnd$randrep" : '';
$outfile ||= "${cond1}_${cond2}_${nm}${cl}${rr}_${test}_test.tsv";
open F, ">$outfile";

# prepare data
print "Preparing data...";
my (@dat, @x1, @x2);
for my $gene (@genes)
{
  $gene =~ tr/A-Z/a-z/;
  my $i1 = $g2i{$cond1}{$gene};
  my $i2 = $g2i{$cond2}{$gene};
  if(defined $i1 && defined $i2)
  {
    my $x1 = $d1(,$i1;-);
    my $x2 = $d2(,$i2;-);

    #print "$x1\n$x2\n" if $gene eq 'rdn5-1';

    my $m1 = mean($x1);
    my $m2 = mean($x2);
    my $fc = log($m2 / $m1) / log(2);

    push @dat, [$gene, $m1, $m2, $fc];
    push @x1, $x1;
    push @x2, $x2;
  }
}
print " done\n";
my $n = @dat;

# perform test
print "Performing test...";
my $Ps = ShrinktTest(pdl(@x1), pdl(@x2)) if $test eq 'st';
for my $i (0 .. $n - 1)
{
  my ($gene, $m1, $m2, $fc) = @{$dat[$i]};
  my $x1 = $x1[$i];
  my $x2 = $x2[$i];

  my $p;
  if($test eq 't')
    {($p) = tTest($x1, $x2)}
  elsif($test eq 'lt')
    {$p = logtTest($x1, $x2)}
  elsif($test eq 'lnt')
    {$p = logntTest($x1, $x2)}
  elsif($test eq 'mw')
    {$p = MannWhitney($x1, $x2, 1)}
  elsif($test eq 'ks')
    {(my $D, $p) = KStwo($x1, $x2)}
  elsif($test eq 'st')
    {$p = at($Ps, $i)}
  #my ($p) = tTest($x1, $x2);
  printf F "%s\t%.4g\t%.4g\t%.4g\t%.4g\n", $gene, $fc, $p, $m1, $m2;
}

print " done\n";
print "\nResults in $outfile\n";

=head1 SYNOPSIS

  simple_de_test.pl -norm=deseq -clean -test=mw

=head1 OPTIONS

=over 4

=item B<-test>=I<[t|lt|st|mw|ks]>

Type of differential expression test.

  t - standard t-test for two samples with identical variances
  lt - log-ratio t-test using approximately normal statistic Z = (log m2 - log m1) / sqrt(((s1/m1)**2)/n1 + ((s2/m2)**2)/n2), where m1, m2 are sample means and s1, s2 are sample standard deviations
  st - shrinkage variance test of Opgen-Rhein and Strimmer (2007)
  mw - Mann-Whitney test
  ks - Kolmogorov-Smirnov test; B<warning> - KS test does not work properly for discrete data!

=item B<-outfile>=I<string>

Output file. If not defined, a default name will be build using condition names and type of test.

=item B<-norm>=I<string>

Expression data normalization. Input expression files contain raw counts. These are normalized on the fly, using one of the following methods:

  none - no normalization
  deseq - DESeq normalization (default)
  tmm - trimmed mean of M values normalization
  fpkm - approximate FPKM normalization (not identical to cuffdiff!)
  totcount - total count
  totcountm - total count with normalization factors scaled to the mean of 1

=item B<-clean>

A switch indicating that only clean replicates should be used. Clean replicates are defined in C<GRNASeq.pm> module.

=item B<-defsfile>=I<string>

Path to defs.dat configuration file.

=item B<-randcond>=I<string>

If specified, test will be performed on randomly selected replicates from the same condition, defined here.

=back


text:
class Repl;

#include "params/SimObject.hh"

struct ReplParams
    : public SimObjectParams
{
};

#endif // __PARAMS__Repl__


text:
module Kruptos
module Noise

  def add_noise(newLength)
    message = self
    usableNoisyMessageLength = newLength / 9 * 8
    bitmapSize = newLength / 9
    remainingBytes = newLength - usableNoisyMessageLength - bitmapSize
    if (message.length > usableNoisyMessageLength)
      minimumNewLength = (message.length / 8.0).ceil * 9
      puts "For a clear text of #{message.length} bytes, the minimum obscured length"
      puts "is #{minimumNewLength} bytes which allows for no noise in the message."
      puts "You should choose an obscured length of at least double the clear text"
      puts "length, such as #{message.length / 8 * 32} bytes"
      raise "Insufficient length for noisy message"
    end
    bitmap = []
    usableNoisyMessageLength.times { bitmap << false }
    srand(Time.now.to_i)
    positionsSelected = 0
    while (positionsSelected < message.length)
      positionTaken = rand(usableNoisyMessageLength)
      if bitmap[positionTaken]
        next
      else
        bitmap[positionTaken] = true
        positionsSelected = positionsSelected.next
      end
    end

    noisyMessage = ""
    0.upto(bitmapSize-1) { |byte|
      c = 0
      0.upto(7) { |bit|
        c = c + (1<<bit) if bitmap[byte * 8 + bit]
      }
      noisyMessage << c.chr
    }
    posInMessage = 0
    0.upto(usableNoisyMessageLength-1) { |pos|
      if bitmap[pos]
        meaningfulByte = message[posInMessage]
        noisyMessage << meaningfulByte
        posInMessage = posInMessage.next
      else
        noiseByte = rand(256).chr
        noisyMessage << noiseByte
      end
    }
    remainingBytes.times {
        noiseByte = rand(256).chr
        noisyMessage << noiseByte
    }
    return(noisyMessage)
  end

  def remove_noise
    noisyMessage = self
    bitmapSize = noisyMessage.length / 9
    actualMessageLength =  bitmapSize * 8

    actualMessageStart = bitmapSize
    actualMessageFinish = bitmapSize + actualMessageLength - 1
    actualMessage = noisyMessage[actualMessageStart..actualMessageFinish]

    bitmap = []
    0.upto(bitmapSize - 1) { |byte|
      c = noisyMessage[byte]
      0.upto(7) { |bit|
        bitmap[byte * 8 + bit] = (c[bit] == 1)
      }
    }
    clearMessage = ""
    0.upto(actualMessageLength) { |pos|
      meaningful = bitmap[pos]
      if meaningful
        clearMessage << actualMessage[pos]
      end
    }
    return(clearMessage)
  end

end
end

class String
  include Kruptos::Noise
end


text:
ForrstBot.database = Sequel.connect(
  :adapter  => 'sqlite',
  :database => File.expand_path('../../database.db', __FILE__),
  :test     => true,
  :encoding => 'utf8'
)

# IMPORTANT, when running MySQL the engine should be set to InnoDB in order for
# foreign keys to work properly.
if ForrstBot.database.adapter_scheme.to_s.include?('mysql')
  Sequel::MySQL.default_engine = 'InnoDB'
end


text:
package ca.laplanete.mobile.example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Page
{

    private List<Item> items = new ArrayList<Item>();

    public List<Item> getItems()
    {
        return items;
    }

    public void setItems(List<Item> items)
    {
        this.items = items;
    }

    public void addItem(Item item)
    {
        items.add(item);
    }

    public void swapItems(int itemA, int itemB)
    {
        Collections.swap(items, itemA, itemB);
    }

    public Item removeItem(int itemIndex)
    {
        Item item = items.get(itemIndex);
        items.remove(itemIndex);
        return item;
    }

    public void deleteItem(int itemIndex)
    {
        items.remove(itemIndex);
    }
}


text:
package info.androidhive.barcodereader;

import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class BarcodeFragmentTestActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_barcode_fragment_test);

        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        BarcodeFragment bf = new BarcodeFragment();
        ft.add(R.id.container, bf);
        ft.commit();
    }
}


text:
package sivl.platform.common.describe;

public interface Describe {

}


text:
//From: https://github.com/w8r/Leaflet.Path.Drag/blob/master/src/Path.Drag.js

/**
 * Leaflet vector features drag functionality
 * @preserve
 */

"use strict";

/**
 * Drag handler
 * @class L.Path.Drag
 * @extends {L.Handler}
 */
L.Handler.PathDrag = L.Handler.extend( /** @lends  L.Path.Drag.prototype */ {

    /**
     * @param  {L.Path} path
     * @varructor
     */
    initialize: function(path) {

        /**
         * @type {L.Path}
         */
        this._path = path;

        /**
         * @type {Array.<Number>}
         */
        this._matrix = null;

        /**
         * @type {L.Point}
         */
        this._startPoint = null;

        /**
         * @type {L.Point}
         */
        this._dragStartPoint = null;

    },

    /**
     * Enable dragging
     */
    addHooks: function() {
        this._path.on("mousedown", this._onDragStart, this);
        if (!L.Path.CANVAS) {
            L.DomUtil.addClass(this._path._container, "leaflet-path-draggable");
        }
    },

    /**
     * Disable dragging
     */
    removeHooks: function() {
        this._path.off("mousedown", this._onDragStart, this);
        if (!L.Path.CANVAS) {
            L.DomUtil.removeClass(this._path._container, "leaflet-path-draggable");
        }
    },

    /**
     * @return {Boolean}
     */
    moved: function() {
        return this._path._dragMoved;
    },

    /**
     * Start drag
     * @param  {L.MouseEvent} evt
     */
    _onDragStart: function(evt) {
        this._startPoint = evt.containerPoint.clone();
        this._dragStartPoint = evt.containerPoint.clone();
        this._matrix = [1, 0, 0, 1, 0, 0];

        this._path._map
            .on("mousemove", this._onDrag, this)
            .on("mouseup", this._onDragEnd, this);
        this._path._dragMoved = false;
    },

    /**
     * Dragging
     * @param  {L.MouseEvent} evt
     */
    _onDrag: function(evt) {
        var x = evt.containerPoint.x;
        var y = evt.containerPoint.y;
        var dx = x - this._startPoint.x;
        var dy = y - this._startPoint.y;
        if (!this._path._dragMoved && (dx || dy)) {
            this._path._dragMoved = true;
            this._path.fire("dragstart");

            if (this._path._popup) {
                this._path._popup._close();
                this._path.off("click", this._path._openPopup, this._path);
            }
        }

        this._matrix[4] += dx;
        this._matrix[5] += dy;

        this._startPoint.x = x;
        this._startPoint.y = y;

        this._path._applyTransform(this._matrix);
        this._path.fire("drag");
        L.DomEvent.stop(evt.originalEvent);
    },

    /**
     * Dragging stopped, apply
     * @param  {L.MouseEvent} evt
     */
    _onDragEnd: function(evt) {
        L.DomEvent.stop(evt);
        // undo container transform
        this._path._resetTransform();
        // apply matrix
        this._transformPoints(this._matrix);

        this._path._map
            .off("mousemove", this._onDrag, this)
            .off("mouseup", this._onDragEnd, this);

        // consistency
        this._path.fire("dragend", {
            distance: Math.sqrt(
                L.LineUtil._sqDist(this._dragStartPoint, evt.containerPoint)
            )
        });

        if (this._path._popup) {
            L.Util.requestAnimFrame(function() {
                this._path.on("click", this._path._openPopup, this._path);
            }, this);
        }

        this._matrix = null;
        this._startPoint = null;
        this._dragStartPoint = null;
        this._path._dragMoved = false;
    },

    /**
     * Applies transformation, does it in one sweep for performance,
     * so don't be surprised about the code repetition.
     *
     * [ x ]   [ a  b  tx ] [ x ]   [ a * x + b * y + tx ]
     * [ y ] = [ c  d  ty ] [ y ] = [ c * x + d * y + ty ]
     *
     * @param {Array.<Number>} matrix
     */
    _transformPoints: function(matrix) {
        var path = this._path;
        var i, number, len, latlng;
        var px = L.point(matrix[4], matrix[5]);
        var crs = path._map.options.crs;
        var transformation = crs.transformation;
        var scale = crs.scale(path._map.getZoom());
        var projection = crs.projection;
        var diff = transformation.untransform(px, scale)
            .subtract(transformation.untransform(L.point(0, 0), scale)); // console.time('transform');

        // all shifts are in-place
        if (path._point) { // L.Circle
            path._latlng = projection.unproject(
                projection.project(path._latlng)._add(diff));
            path._point._add(px);
        } else if (path._originalPoints) { // everything else
            for (i = 0, len = path._originalPoints.length; i < len; i++) {
                latlng = path._latlngs[i];
                path._latlngs[i] = projection
                    .unproject(projection.project(latlng)._add(diff));
                path._originalPoints[i]._add(px);
            }
        }

        // holes operations
        if (path._holes) {
            for (i = 0, len = path._holes.length; i < len; i++) {
                for (var j = 0, len2 = path._holes[i].length; j < len2; j++) {
                    latlng = path._holes[i][j];
                    path._holes[i][j] = projection
                        .unproject(projection.project(latlng)._add(diff));
                    path._holePoints[i][j]._add(px);
                }
            }
        }

        // console.timeEnd('transform');

        path._updatePath();
    }

});

L.Path.prototype.__initEvents = L.Path.prototype._initEvents;
L.Path.prototype._initEvents = function() {
    this.__initEvents();

    if (this.options.draggable) {
        if (this.dragging) {
            this.dragging.enable();
        } else {
            this.dragging = new L.Handler.PathDrag(this);
            this.dragging.enable();
        }
    } else if (this.dragging) {
        this.dragging.disable();
    }
};


text:
//
//  DJIInspireMainController.h
//  DJISDK
//
//  Copyright (c) 2015 DJI. All rights reserved.
//

#import <DJISDK/DJIMainController.h>
#import <DJISDK/DJIHotPointMission.h>
#import <DJISDK/DJIGroundStation.h>
#import <DJISDK/DJIFollowMeMission.h>
#import <DJISDK/DJIIOCMission.h>

@interface DJIInspireMainController : DJIMainController

/**
 *  Main controller's firmware version.
 *
 */
-(NSString*) getMainControllerVersion;

/**
 *  Start update main controller's system state
 */
-(void) startUpdateMCSystemState;

/**
 *  Stop update main controller's system state
 */
-(void) stopUpdateMCSystemState;

/**
 *  Open landing gear protection. If opened, the landing gear will drop down automatically while the drone landing
 *
 *  @param block Remote execute reult
 */
-(void) openLandingGearProtectionWithResult:(DJIExecuteResultBlock)block;

/**
 *  Close landing gear protection
 *
 *  @param block Remote execute reult
 */
-(void) closeLandingGearProtectionWithResult:(DJIExecuteResultBlock)block;

/**
 *  Set dynamic home point enable
 *
 *  @param enable Dynamic home point enable
 *  @param block  Remote execute result.
 */
-(void) setDynamicHomePointEnable:(BOOL)enable withResult:(DJIExecuteResultBlock)block DJI_API_DEPRECATED;

/**
 *  Enter transport mode. if receive ERR_CommandExecuteFailed error, that maybe the gimbal is not dismount or the ground is not flattening.
 *
 *  @param block Remote execute result.
 */
-(void) enterTransportModeWithResult:(DJIExecuteResultBlock)block;

/**
 *  Exit transport mode.
 *
 *  @param block Remote execute result.
 */
-(void) exitTransportModeWithResult:(DJIExecuteResultBlock)block;

/**
 *  Set multiple flight mode open. if set open, then the remote controller's mode switch will be available.
 *
 *  @param isOpen   Whether or not open the multiple flight mode.
 *  @param block    Remote execute result.
 */
-(void) setMultipleFlightModeOpen:(BOOL)isOpen withResult:(DJIExecuteResultBlock)block;

/*
 *  Set low battery waning data.
 *
 *  @param percent Percentage of low battery in range [25, 50].
 *  @param block   Remote execute result.
 */
-(void) setLowBatteryWarning:(uint8_t)percent withResult:(DJIExecuteResultBlock)block;

/**
 *  Get low battery warning data.
 *
 *  @param result Remote execute result.
 */
-(void) getLowBatteryWarningWithResult:(void(^)(uint8_t percent, DJIError* error))result;

/**
 *  Set serious low battery waning data, percentage of voltage in range [10, 25].
 *
 *  @param percent Percentage of serious low battery
 *  @param block   Remote execute result.
 */
-(void) setSeriousLowBattery:(uint8_t)percent withResult:(DJIExecuteResultBlock)block;

/**
 *  Get serious low battery warning data.
 *
 *  @param result Remote execute result.
 */
-(void) getSeriousLowBatteryWarningwithResult:(void(^)(uint8_t percent, DJIError* error))result;

/**
 *  Set home point use the aircraft's current location.
 *
 *  @param result Remote execute result.
 */
-(void) setHomePointUsingAircraftCurrentLocationWithResult:(DJIExecuteResultBlock)result;

/**
 *  Set aircraft name. the length of aircraft name should be less than 32 characters
 *
 *  @param name   Name to be set to the aricraft.
 *  @param result Remote execute result.
 */
-(void) setAircraftName:(NSString*)name withResult:(DJIExecuteResultBlock)result;

/**
 *  Get aircraft name.
 *
 *  @param result Remote execute result.
 */
-(void) getAircraftNameWithResult:(void(^)(NSString* name, DJIError* error))result;

/**
 *  Send data to external device. Only support in product Matrice100.
 *
 *  @param data  Data to be sent to external device, the size of data should not large then 100 byte.
 *  @param block Remote execute result.
 */
-(void) sendDataToExternalDevice:(NSData*)data withResult:(DJIExecuteResultBlock)block;

@end


text:
/*
 */

package naoscp.tools;

import java.awt.Component;
import java.awt.Container;

/**
 *
 * @author Heinrich Mellmann
 */
public class SwingTools
{
    public static void setEnabled(Component component, boolean enabled) {
        component.setEnabled(enabled);
        if (component instanceof Container) {
            for (Component child : ((Container) component).getComponents()) {
                setEnabled(child, enabled);
            }
        }
    }
}


text:
namespace app { namespace Fuse { namespace Animations { struct AnimatorState; } } }
namespace app { namespace Fuse { namespace Animations { struct Converter__Fuse_Elements_CachingMode; } } }
namespace app { namespace Fuse { namespace Animations { struct CreateStateParams; } } }
namespace app { namespace Uno { namespace UX { struct Property__Fuse_Elements_CachingMode; } } }
namespace app { namespace Uno { struct Float2; } }

namespace app {
namespace Fuse {
namespace Animations {

struct Change__Fuse_Elements_CachingMode;

struct Change__Fuse_Elements_CachingMode__uType : ::app::Fuse::Animations::TrackAnimator__uType
{
};

Change__Fuse_Elements_CachingMode__uType* Change__Fuse_Elements_CachingMode__typeof();

void Change__Fuse_Elements_CachingMode___ObjInit_2(Change__Fuse_Elements_CachingMode* __this, ::app::Uno::UX::Property__Fuse_Elements_CachingMode* target);
::app::Fuse::Animations::AnimatorState* Change__Fuse_Elements_CachingMode__CreateState(Change__Fuse_Elements_CachingMode* __this, ::app::Fuse::Animations::CreateStateParams* p);
float Change__Fuse_Elements_CachingMode__get_DegreesX(Change__Fuse_Elements_CachingMode* __this);
::app::Uno::Float2 Change__Fuse_Elements_CachingMode__get_DegreesXY(Change__Fuse_Elements_CachingMode* __this);
float Change__Fuse_Elements_CachingMode__get_DegreesY(Change__Fuse_Elements_CachingMode* __this);
float Change__Fuse_Elements_CachingMode__get_DegreesZ(Change__Fuse_Elements_CachingMode* __this);
bool Change__Fuse_Elements_CachingMode__get_IsContinuous(Change__Fuse_Elements_CachingMode* __this);
::app::Uno::UX::Property__Fuse_Elements_CachingMode* Change__Fuse_Elements_CachingMode__get_Target(Change__Fuse_Elements_CachingMode* __this);
int Change__Fuse_Elements_CachingMode__get_Value(Change__Fuse_Elements_CachingMode* __this);
float Change__Fuse_Elements_CachingMode__get_X(Change__Fuse_Elements_CachingMode* __this);
::app::Uno::Float2 Change__Fuse_Elements_CachingMode__get_XY(Change__Fuse_Elements_CachingMode* __this);
float Change__Fuse_Elements_CachingMode__get_Y(Change__Fuse_Elements_CachingMode* __this);
float Change__Fuse_Elements_CachingMode__get_Z(Change__Fuse_Elements_CachingMode* __this);
Change__Fuse_Elements_CachingMode* Change__Fuse_Elements_CachingMode__New_1(::uStatic* __this, ::app::Uno::UX::Property__Fuse_Elements_CachingMode* target);
void Change__Fuse_Elements_CachingMode__set_DegreesX(Change__Fuse_Elements_CachingMode* __this, float value);
void Change__Fuse_Elements_CachingMode__set_DegreesXY(Change__Fuse_Elements_CachingMode* __this, ::app::Uno::Float2 value);
void Change__Fuse_Elements_CachingMode__set_DegreesY(Change__Fuse_Elements_CachingMode* __this, float value);
void Change__Fuse_Elements_CachingMode__set_DegreesZ(Change__Fuse_Elements_CachingMode* __this, float value);
void Change__Fuse_Elements_CachingMode__set_Target(Change__Fuse_Elements_CachingMode* __this, ::app::Uno::UX::Property__Fuse_Elements_CachingMode* value);
void Change__Fuse_Elements_CachingMode__set_Value(Change__Fuse_Elements_CachingMode* __this, int value);
void Change__Fuse_Elements_CachingMode__set_X(Change__Fuse_Elements_CachingMode* __this, float value);
void Change__Fuse_Elements_CachingMode__set_XY(Change__Fuse_Elements_CachingMode* __this, ::app::Uno::Float2 value);
void Change__Fuse_Elements_CachingMode__set_Y(Change__Fuse_Elements_CachingMode* __this, float value);
void Change__Fuse_Elements_CachingMode__set_Z(Change__Fuse_Elements_CachingMode* __this, float value);

struct Change__Fuse_Elements_CachingMode : ::app::Fuse::Animations::TrackAnimator
{
    ::uStrong< ::app::Fuse::Animations::Converter__Fuse_Elements_CachingMode*> ContinuousConverter;
    ::uStrong< ::app::Uno::UX::Property__Fuse_Elements_CachingMode*> _Target;

    void _ObjInit_2(::app::Uno::UX::Property__Fuse_Elements_CachingMode* target) { Change__Fuse_Elements_CachingMode___ObjInit_2(this, target); }
    float DegreesX() { return Change__Fuse_Elements_CachingMode__get_DegreesX(this); }
    ::app::Uno::Float2 DegreesXY();
    float DegreesY() { return Change__Fuse_Elements_CachingMode__get_DegreesY(this); }
    float DegreesZ() { return Change__Fuse_Elements_CachingMode__get_DegreesZ(this); }
    bool IsContinuous() { return Change__Fuse_Elements_CachingMode__get_IsContinuous(this); }
    ::app::Uno::UX::Property__Fuse_Elements_CachingMode* Target() { return Change__Fuse_Elements_CachingMode__get_Target(this); }
    int Value() { return Change__Fuse_Elements_CachingMode__get_Value(this); }
    float X() { return Change__Fuse_Elements_CachingMode__get_X(this); }
    ::app::Uno::Float2 XY();
    float Y() { return Change__Fuse_Elements_CachingMode__get_Y(this); }
    float Z() { return Change__Fuse_Elements_CachingMode__get_Z(this); }
    void DegreesX(float value) { Change__Fuse_Elements_CachingMode__set_DegreesX(this, value); }
    void DegreesXY(::app::Uno::Float2 value);
    void DegreesY(float value) { Change__Fuse_Elements_CachingMode__set_DegreesY(this, value); }
    void DegreesZ(float value) { Change__Fuse_Elements_CachingMode__set_DegreesZ(this, value); }
    void Target(::app::Uno::UX::Property__Fuse_Elements_CachingMode* value) { Change__Fuse_Elements_CachingMode__set_Target(this, value); }
    void Value(int value) { Change__Fuse_Elements_CachingMode__set_Value(this, value); }
    void X(float value) { Change__Fuse_Elements_CachingMode__set_X(this, value); }
    void XY(::app::Uno::Float2 value);
    void Y(float value) { Change__Fuse_Elements_CachingMode__set_Y(this, value); }
    void Z(float value) { Change__Fuse_Elements_CachingMode__set_Z(this, value); }
};

}}}

#include <app/Uno.Float2.h>

namespace app {
namespace Fuse {
namespace Animations {

inline ::app::Uno::Float2 Change__Fuse_Elements_CachingMode::DegreesXY() { return Change__Fuse_Elements_CachingMode__get_DegreesXY(this); }
inline ::app::Uno::Float2 Change__Fuse_Elements_CachingMode::XY() { return Change__Fuse_Elements_CachingMode__get_XY(this); }
inline void Change__Fuse_Elements_CachingMode::DegreesXY(::app::Uno::Float2 value) { Change__Fuse_Elements_CachingMode__set_DegreesXY(this, value); }
inline void Change__Fuse_Elements_CachingMode::XY(::app::Uno::Float2 value) { Change__Fuse_Elements_CachingMode__set_XY(this, value); }

}}}

#endif


text:
require 'spec_helper'

describe 'sentry::server' do
  context 'supported operating systems' do
    on_supported_os.each do |os, facts|
      context "on #{os}" do
        let(:facts) do
          facts
        end

        context "without any parameters" do
          it { is_expected.to compile.with_all_deps }

          it { is_expected.to contain_class('sentry::server') }
          it { is_expected.to contain_class('sentry::server::install').that_comes_before('sentry::server::config') }
          it { is_expected.to contain_class('sentry::server::config') }
          it { is_expected.to contain_class('sentry::server::service').that_subscribes_to('sentry::server::config') }

          it { is_expected.to contain_file('/etc/sentry/conf/sentry-site.xml') }
          it { is_expected.to contain_service('sentry-store') }
          it { is_expected.to contain_package('sentry-store').with_ensure('present') }
        end
      end
    end
  end
end


text:
using System.Collections.Generic;

namespace Coevery.DisplayManagement.Descriptors {
    public class ShapeTable {
        public IDictionary<string, ShapeDescriptor> Descriptors { get; set; }
        public IDictionary<string, ShapeBinding> Bindings { get; set; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://your.testhost.com/" />
<title>Load Module with httpRequest Attribute Specified</title>

Load Module with httpRequest Attribute Specified

	open
	/decjtest/page/decjModuleLoad/testLoadModuleHttpRequestAttr.htm

	waitForText
	id=moduleLoadState
	done

	verifyText
	id=title
	decj Framework


text:
TARGET = bin/c-demo
CC = g++
CFLAGS = -O2 -Wall -c

#define SRC_ROOT OBJ_ROOT BIN_ROOT
SRC_ROOT = src
OBJ_ROOT = obj
BIN_ROOT = bin

#find all the src dirs, and create the obj dirs accordingly
SRCDIR = $(shell find $(SRC_ROOT) -type d)
OBJDIR = $(foreach srcdir, $(SRCDIR),$(subst $(SRC_ROOT),$(OBJ_ROOT),$(srcdir)))

#include the dir for head file
INCDIR = $(shell find include -type d)
INCLUDE_FLAG := $(foreach dir, $(INCDIR),-I$(dir))

#find all the c source and create all the object accordingly
SOURCES := $(foreach dir, $(SRCDIR),$(wildcard $(dir)/*.cpp))
OBJECTS := $(subst $(SRC_ROOT),$(OBJ_ROOT),$(SOURCES:.cpp=.o))

$(TARGET):$(SOURCES)
	@echo "\n===compile *.src to *.o"
	@mkdir -p $(BIN_ROOT) $(OBJDIR)
	$(foreach src, $^,$(CC) $(INCLUDE_FLAG) $(CFLAGS) $(src) -o $(subst $(SRC_ROOT),$(OBJ_ROOT),$(src:.cpp=.o)); )
	@echo "\n===link *.o to "$(TARGET)
	$(CC) $(foreach obj,$(OBJECTS),$(obj)) -o $(TARGET)

debug:$(TARGET)

run:$(TARGET)
	@./$(TARGET)

JAVA_SRC := $(foreach dir, $(SRCDIR),$(wildcard $(dir)/*.java))
JAVA_OBJ := $(JAVA_SRC:.java=.class)
$(JAVA_OBJ):%.class:%.java
	@echo "java compile"
	javac -d $(subst $(SRC_ROOT),$(OBJ_ROOT),$(dir $@)) $<

test:
	@echo SOURCES:$(SOURCES)
	@echo OBJECTS:$(OBJECTS)
	@echo JAVA_SRC:$(JAVA_SRC)
	@echo JAVA_OBJ:$(JAVA_OBJ)
	@echo INCDIR:$(INCDIR)
	@echo INCLUDE_FLAG:$(INCLUDE_FLAG)
	@echo VPATH:$(VPATH)
.PHONY: clean
clean:
	@rm -rvf $(OBJ_ROOT)
	@rm -rvf $(BIN_ROOT)


text:
package com.thoughtworks.xstream.converters.basic;

/**
 * Converts a short primitive or {@link Short} wrapper to a string.
 *
 * @author Joe Walnes
 */
public class ShortConverter extends AbstractSingleValueConverter {

    @Override
    public boolean canConvert(final Class<?> type) {
        return type.equals(short.class) || type.equals(Short.class);
    }

    @Override
    public Object fromString(final String str) {
        final int value = Integer.decode(str).intValue();
        if (value < Short.MIN_VALUE || value > 0xFFFF) {
            throw new NumberFormatException("For input string: \"" + str + '"');
        }
        return new Short((short)value);
    }

}


text:
.module {
    border-bottom-style: dotted;
    border-bottom-width: 1px;
	border-color: #e1e1e1;
    margin: 10px;
    padding-bottom: 20px;
}

.module_head {
    margin-bottom: 10px;
	font-size: 1.7em;
}

.module_head ul {
    font-size: 0.6em;
	float: right;
}

.module_head ul, .module_head ul li {
	display: inline-block;
	height: 20px;
}

.module_head span {
	font-size: 0.7em;
	margin-left: 10px;
	padding-left: 19px;
	background-image:url('/media/i/chart.png');
	background-repeat: no-repeat;
	text-decoration: none;
	color: #000;
}

li.mod_github a {
	display: inline-block;
	padding-left: 19px;
	background-image:url('/media/i/chain.png');
	background-repeat: no-repeat;
	text-decoration: none;
	margin-right: 15px;
	height: 100%;
	color: #000;
}

li.mod_watch {
	padding-left: 19px;
	background-image:url('/media/i/eye.png');
	background-repeat: no-repeat;
	margin-right: 15px;
	height: 100%;
}

li.mod_forks {
	padding-left: 19px;
	background-image:url('/media/i/share.png');
	background-repeat: no-repeat;
	margin-right: 15px;
	height: 100%;
}

.module_desc {
    padding-left: 10px;
	margin-bottom: 20px;
}

.module_foot {
    font-size: 0.8em;
	height: 20px;
}

.module_foot ul, .module_foot ul li {
    display: inline-block;
	height: 100%;
}

.module_foot ul li {
	margin-right: 4px;
}

li.mod_cat a {
	display: inline-block;
	padding-left: 19px;
	background-image:url('/media/i/category.png');
	background-repeat: no-repeat;
	text-decoration: none;
	height: 100%;
	color: #000;
}

li.mod_tag a {
	display: inline-block;
	padding-left: 19px;
	background-image:url('/media/i/tag.png');
	background-repeat: no-repeat;
	text-decoration: none;
	height: 100%;
	color: #000;
}


text:
package cn.fireworkstudio.java.springboot.ch2.profile;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Configuration
public class ProfileConfig {
    @Bean
    @Profile("dev") //1
    public DemoBean devDemoBean() {
        return new DemoBean("from development profile");
    }

    @Bean
    @Profile("prod") //2
    public DemoBean prodDemoBean() {
        return new DemoBean("from production profile");
    }
}


text:
YUI.add('series-area-stacked', function (Y, NAME) {

/**
 * Provides functionality for creating a stacked area series.
 *
 * @module charts
 * @submodule series-area-stacked
 */
/**
 * StackedAreaSeries area fills to display data showing its contribution to a whole.
 *
 * @class StackedAreaSeries
 * @extends AreaSeries
 * @uses StackingUtil
 * @constructor
 * @param {Object} config (optional) Configuration parameters.
 * @submodule series-area-stacked
 */
Y.StackedAreaSeries = Y.Base.create("stackedAreaSeries", Y.AreaSeries, [Y.StackingUtil], {
    /**
     * @protected
     *
     * Calculates the coordinates for the series. Overrides base implementation.
     *
     * @method setAreaData
     */
    setAreaData: function()
    {
        Y.StackedAreaSeries.superclass.setAreaData.apply(this);
        this._stackCoordinates.apply(this);
    },

    /**
     * @protected
     *
     * Draws the series
     *
     * @method drawSeries
     */
	drawSeries: function()
    {
        this.drawFill.apply(this, this._getStackedClosingPoints());
    }
}, {
    ATTRS: {
        /**
         * Read-only attribute indicating the type of series.
         *
         * @attribute type
         * @type String
         * @default stackedArea
         */
        type: {
            value:"stackedArea"
        }
    }
});

}, 'patched-v3.18.0', {"requires": ["series-stacked", "series-area"]});