text:
import {Meteor} from 'meteor/meteor';
import {HTTP} from 'meteor/http';

import _ from 'lodash';
import moment from 'moment';
import request from 'request';

import {Collections, collectionDefinitions} from '/lib/collections';

export default function () {

  Meteor.methods({

    'createImportSettingsTemplate': function (user, name, settings) {
      //console.log('create import', user, name, settings);
      return Collections['magic.import.settings.templates'].insert({
        _user: user,
        _name: name,
        _inserted: moment().utc().toISOString(),
        settings: settings
      }, (error) => { console.log('create import', error)});
    },

    'saveImportSettingsTemplate': function (user, ID, settings) {
      //console.log('save import', user, ID, settings);
      Collections['magic.import.settings.templates'].update({
        _id: ID,
        _user: user
      }, {
        $set: { settings: settings }
      }, (error) => { console.log('save import', error)});
    },

    'renameImportSettingsTemplate': function (user, ID, name) {
      //console.log('rename import', user, ID, name);
      Collections['magic.import.settings.templates'].update({
        _id: ID,
        _user: user
      }, {
        $set: { _name: name }
      }, (error) => { console.log('rename import', error)});
    },

    'deleteImportSettingsTemplate': function (user, ID) {
      //console.log('delete import', user, ID);
      Collections['magic.import.settings.templates'].remove({
        _id: ID,
        _user: user
      }, (error) => { console.log('delete import', error)});
    },

    'getImportSettingsTemplates': function (user) {
      console.log('getImportSettingsTemplates', user);
      let templates = Collections['magic.import.settings.templates'].find(
        {_user: user},
        {sort: {'_inserted': -1}}).fetch();
      console.log('getImportSettingsTemplates', user, templates);
      return templates;
    },

    'getImportSettingsTemplate': function (ID) {
      return Collections['magic.import.settings.templates'].findOne(ID);
    },

    async magicGetPmagPyPlotFiles(cID, user, limit, attempt = 0) {
      this.unblock();
      //console.log("magicGetPmagPyPlotFiles", attempt, `http://pmagpy.earthref.org/plots/${cID}`);

      try {
        return await new Promise(resolve => {
          Meteor.call("s3ListObjects", {
            bucket: "magic-plots",
            prefix: `${cID}/`,
            limit
          }, (error, objects) => {
            resolve(_.map(objects, 'Key'));
          });
        });
      } catch (e) {
        console.error("magicGetPmagPyPlotFiles", `Failed to retrieve PmagPy plot files for contribution ${cID}`, e);
        throw new Meteor.Error("magicGetPmagPyPlotFiles", `Failed to retrieve PmagPy plot files for contribution ${cID}`);
      }
    },

    async magicGetPmagPyPlot(file, user, attempt = 0) {
      this.unblock();
      //console.log("magicGetPmagPyPlot", attempt, file);

      try {
        return await new Promise(resolve => {
          Meteor.call("s3GetObjectBase64", {
            bucket: "magic-plots",
            key: file
          }, (error, base64) => {
            resolve(base64);
          });
        });
      } catch (e) {
        console.error("magicGetPmagPyPlot", `Failed to retrieve PmagPy plot ${file}`, e);
        throw new Meteor.Error("magicGetPmagPyPlot", `Failed to retrieve PmagPy plot ${file}`);
      }
    },

    async magicGetPrivateContribution(id, user, attempt = 0) {
      this.unblock();
      console.log("magicGetPrivateContribution", id, user, attempt);

      try {
        return await Meteor.call("s3GetObject", {
          bucket: `magic-private-contributions/${id}`,
          key: `magic_contribution_${id}.txt`,
          encoding: 'utf-8'
        });
      } catch (e) {
        // console.error("magicGetPrivateContribution", `Failed to retrieve private contribution for ${id}`, e);
        throw new Meteor.Error("magicGetPrivateContribution", `Failed to retrieve private contribution for ${id}`);
      }
    },

    async magicGetPrivateContributionZip(id, user, attempt = 0) {
      this.unblock();
      console.log("magicGetPrivateContributionZip", id, user, attempt);

      try {
        return await Meteor.call("s3GetObject", {
          bucket: `magic-private-contributions/${id}`,
          key: `magic_contribution_${id}.zip`
        });
      } catch (e) {
        // console.error("magicGetPrivateContributionZip", `Failed to retrieve private contribution for ${id}`, e);
        throw new Meteor.Error("magicGetPrivateContributionZip", `Failed to retrieve private contribution for ${id}`);
      }
    },

    async magicGetPublicContributions(ids, fileName, user, attempt = 0) {
      this.unblock();
      console.log("magicGetPublicContributions", ids, fileName, user, attempt);

      try {
        return await Meteor.call("s3GetObjectsZip", {
          fileName,
          objects: ids.map(id => {
            return {
              bucket: `magic-activated-contributions/${id}`,
              key: `magic_contribution_${id}.txt`
            };
          })
        });
      } catch (e) {
        console.error("magicGetPublicContributions", `Failed to retrieve private contributions for IDs ${ids.join(', ')}`, e);
        // throw new Meteor.Error("magicGetPublicContributions", `Failed to retrieve private contributions for IDs ${ids.join(', ')}`);
      }
    }

  });

};


text:
'''
Test to  make sure generated datasets are sane.
'''

# needed for python 3 compatibility
from __future__ import absolute_import, division

try:
    import unittest2 as unittest
except ImportError:
    import unittest

from datetime import datetime

import numpy as np
import quantities as pq

from neo.core import (class_by_name, Block, Segment,
                      RecordingChannelGroup, RecordingChannel, Unit,
                      AnalogSignal, AnalogSignalArray,
                      IrregularlySampledSignal, SpikeTrain,
                      Event, Epoch, Spike,
                      EventArray, EpochArray)
from neo.test.generate_datasets import (generate_one_simple_block,
                                        generate_one_simple_segment,
                                        generate_from_supported_objects,
                                        get_fake_value, get_fake_values,
                                        fake_neo, TEST_ANNOTATIONS)
from neo.test.tools import assert_arrays_equal, assert_neo_object_is_compliant

class Test__generate_one_simple_segment(unittest.TestCase):
    def test_defaults(self):
        res = generate_one_simple_segment()

        self.assertTrue(isinstance(res, Segment))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.analogsignals), 0)
        self.assertEqual(len(res.analogsignalarrays), 0)
        self.assertEqual(len(res.irregularlysampledsignals), 0)
        self.assertEqual(len(res.spiketrains), 0)
        self.assertEqual(len(res.spikes), 0)
        self.assertEqual(len(res.events), 0)
        self.assertEqual(len(res.epochs), 0)
        self.assertEqual(len(res.eventarrays), 0)
        self.assertEqual(len(res.epocharrays), 0)

    def test_all_supported(self):
        objects = [Block, Segment,
                   RecordingChannelGroup, RecordingChannel, Unit,
                   AnalogSignal, AnalogSignalArray,
                   IrregularlySampledSignal, SpikeTrain,
                   Event, Epoch, Spike,
                   EventArray, EpochArray]

        res = generate_one_simple_segment(supported_objects=objects)

        self.assertTrue(isinstance(res, Segment))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.analogsignals), 4)
        self.assertEqual(len(res.analogsignalarrays), 0)
        self.assertEqual(len(res.irregularlysampledsignals), 0)
        self.assertEqual(len(res.spiketrains), 6)
        self.assertEqual(len(res.spikes), 0)
        self.assertEqual(len(res.events), 0)
        self.assertEqual(len(res.epochs), 0)
        self.assertEqual(len(res.eventarrays), 3)
        self.assertEqual(len(res.epocharrays), 2)

    def test_half_supported(self):
        objects = [Segment,
                   IrregularlySampledSignal, SpikeTrain,
                   Epoch, Spike,
                   EpochArray]

        res = generate_one_simple_segment(supported_objects=objects)

        self.assertTrue(isinstance(res, Segment))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.analogsignals), 0)
        self.assertEqual(len(res.analogsignalarrays), 0)
        self.assertEqual(len(res.irregularlysampledsignals), 0)
        self.assertEqual(len(res.spiketrains), 6)
        self.assertEqual(len(res.spikes), 0)
        self.assertEqual(len(res.events), 0)
        self.assertEqual(len(res.epochs), 0)
        self.assertEqual(len(res.eventarrays), 0)
        self.assertEqual(len(res.epocharrays), 2)

    def test_all_without_block(self):
        objects = [Segment,
                   RecordingChannelGroup, RecordingChannel, Unit,
                   AnalogSignal, AnalogSignalArray,
                   IrregularlySampledSignal, SpikeTrain,
                   Event, Epoch, Spike,
                   EventArray, EpochArray]

        res = generate_one_simple_segment(supported_objects=objects)

        self.assertTrue(isinstance(res, Segment))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.analogsignals), 4)
        self.assertEqual(len(res.analogsignalarrays), 0)
        self.assertEqual(len(res.irregularlysampledsignals), 0)
        self.assertEqual(len(res.spiketrains), 6)
        self.assertEqual(len(res.spikes), 0)
        self.assertEqual(len(res.events), 0)
        self.assertEqual(len(res.epochs), 0)
        self.assertEqual(len(res.eventarrays), 3)
        self.assertEqual(len(res.epocharrays), 2)

    def test_all_without_segment_valueerror(self):
        objects = [Block,
                   RecordingChannelGroup, RecordingChannel, Unit,
                   AnalogSignal, AnalogSignalArray,
                   IrregularlySampledSignal, SpikeTrain,
                   Event, Epoch, Spike,
                   EventArray, EpochArray]

        self.assertRaises(ValueError, generate_one_simple_segment,
                          supported_objects=objects)

class Test__generate_one_simple_block(unittest.TestCase):
    def test_defaults(self):
        res = generate_one_simple_block()

        self.assertTrue(isinstance(res, Block))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.segments), 0)

    def test_all_supported(self):
        objects = [Block, Segment,
                   RecordingChannelGroup, RecordingChannel, Unit,
                   AnalogSignal, AnalogSignalArray,
                   IrregularlySampledSignal, SpikeTrain,
                   Event, Epoch, Spike,
                   EventArray, EpochArray]

        res = generate_one_simple_block(supported_objects=objects)

        self.assertTrue(isinstance(res, Block))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.segments), 3)
        seg1, seg2, seg3 = res.segments

        self.assertEqual(len(seg1.analogsignals), 4)
        self.assertEqual(len(seg1.analogsignalarrays), 0)
        self.assertEqual(len(seg1.irregularlysampledsignals), 0)
        self.assertEqual(len(seg1.spiketrains), 6)
        self.assertEqual(len(seg1.spikes), 0)
        self.assertEqual(len(seg1.events), 0)
        self.assertEqual(len(seg1.epochs), 0)
        self.assertEqual(len(seg1.eventarrays), 3)
        self.assertEqual(len(seg1.epocharrays), 2)

        self.assertEqual(len(seg2.analogsignals), 4)
        self.assertEqual(len(seg2.analogsignalarrays), 0)
        self.assertEqual(len(seg2.irregularlysampledsignals), 0)
        self.assertEqual(len(seg2.spiketrains), 6)
        self.assertEqual(len(seg2.spikes), 0)
        self.assertEqual(len(seg2.events), 0)
        self.assertEqual(len(seg2.epochs), 0)
        self.assertEqual(len(seg2.eventarrays), 3)
        self.assertEqual(len(seg2.epocharrays), 2)

        self.assertEqual(len(seg3.analogsignals), 4)
        self.assertEqual(len(seg3.analogsignalarrays), 0)
        self.assertEqual(len(seg3.irregularlysampledsignals), 0)
        self.assertEqual(len(seg3.spiketrains), 6)
        self.assertEqual(len(seg3.spikes), 0)
        self.assertEqual(len(seg3.events), 0)
        self.assertEqual(len(seg3.epochs), 0)
        self.assertEqual(len(seg3.eventarrays), 3)
        self.assertEqual(len(seg3.epocharrays), 2)

    def test_half_supported(self):
        objects = [Block, Segment,
                   IrregularlySampledSignal, SpikeTrain,
                   Epoch, Spike,
                   EpochArray]

        res = generate_one_simple_block(supported_objects=objects)

        self.assertTrue(isinstance(res, Block))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.segments), 3)
        seg1, seg2, seg3 = res.segments

        self.assertEqual(len(seg1.analogsignals), 0)
        self.assertEqual(len(seg1.analogsignalarrays), 0)
        self.assertEqual(len(seg1.irregularlysampledsignals), 0)
        self.assertEqual(len(seg1.spiketrains), 6)
        self.assertEqual(len(seg1.spikes), 0)
        self.assertEqual(len(seg1.events), 0)
        self.assertEqual(len(seg1.epochs), 0)
        self.assertEqual(len(seg1.eventarrays), 0)
        self.assertEqual(len(seg1.epocharrays), 2)

        self.assertEqual(len(seg2.analogsignals), 0)
        self.assertEqual(len(seg2.analogsignalarrays), 0)
        self.assertEqual(len(seg2.irregularlysampledsignals), 0)
        self.assertEqual(len(seg2.spiketrains), 6)
        self.assertEqual(len(seg2.spikes), 0)
        self.assertEqual(len(seg2.events), 0)
        self.assertEqual(len(seg2.epochs), 0)
        self.assertEqual(len(seg2.eventarrays), 0)
        self.assertEqual(len(seg2.epocharrays), 2)

        self.assertEqual(len(seg3.analogsignals), 0)
        self.assertEqual(len(seg3.analogsignalarrays), 0)
        self.assertEqual(len(seg3.irregularlysampledsignals), 0)
        self.assertEqual(len(seg3.spiketrains), 6)
        self.assertEqual(len(seg3.spikes), 0)
        self.assertEqual(len(seg3.events), 0)
        self.assertEqual(len(seg3.epochs), 0)
        self.assertEqual(len(seg3.eventarrays), 0)
        self.assertEqual(len(seg3.epocharrays), 2)

    def test_all_without_segment(self):
        objects = [Block,
                   RecordingChannelGroup, RecordingChannel, Unit,
                   AnalogSignal, AnalogSignalArray,
                   IrregularlySampledSignal, SpikeTrain,
                   Event, Epoch, Spike,
                   EventArray, EpochArray]

        res = generate_one_simple_block(supported_objects=objects)

        self.assertTrue(isinstance(res, Block))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.segments), 0)

    def test_all_without_block_valueerror(self):
        objects = [Segment,
                   RecordingChannelGroup, RecordingChannel, Unit,
                   AnalogSignal, AnalogSignalArray,
                   IrregularlySampledSignal, SpikeTrain,
                   Event, Epoch, Spike,
                   EventArray, EpochArray]

        self.assertRaises(ValueError, generate_one_simple_block,
                          supported_objects=objects)

class Test__generate_from_supported_objects(unittest.TestCase):
    def test_no_object_valueerror(self):
        objects = []

        self.assertRaises(ValueError, generate_from_supported_objects, objects)

    def test_all(self):
        objects = [Block, Segment,
                   RecordingChannelGroup, RecordingChannel, Unit,
                   AnalogSignal, AnalogSignalArray,
                   IrregularlySampledSignal, SpikeTrain,
                   Event, Epoch, Spike,
                   EventArray, EpochArray]

        res = generate_from_supported_objects(objects)

        self.assertTrue(isinstance(res, Block))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.segments), 3)
        seg1, seg2, seg3 = res.segments

        self.assertEqual(len(seg1.analogsignals), 4)
        self.assertEqual(len(seg1.analogsignalarrays), 0)
        self.assertEqual(len(seg1.irregularlysampledsignals), 0)
        self.assertEqual(len(seg1.spiketrains), 6)
        self.assertEqual(len(seg1.spikes), 0)
        self.assertEqual(len(seg1.events), 0)
        self.assertEqual(len(seg1.epochs), 0)
        self.assertEqual(len(seg1.eventarrays), 3)
        self.assertEqual(len(seg1.epocharrays), 2)

        self.assertEqual(len(seg2.analogsignals), 4)
        self.assertEqual(len(seg2.analogsignalarrays), 0)
        self.assertEqual(len(seg2.irregularlysampledsignals), 0)
        self.assertEqual(len(seg2.spiketrains), 6)
        self.assertEqual(len(seg2.spikes), 0)
        self.assertEqual(len(seg2.events), 0)
        self.assertEqual(len(seg2.epochs), 0)
        self.assertEqual(len(seg2.eventarrays), 3)
        self.assertEqual(len(seg2.epocharrays), 2)

        self.assertEqual(len(seg3.analogsignals), 4)
        self.assertEqual(len(seg3.analogsignalarrays), 0)
        self.assertEqual(len(seg3.irregularlysampledsignals), 0)
        self.assertEqual(len(seg3.spiketrains), 6)
        self.assertEqual(len(seg3.spikes), 0)
        self.assertEqual(len(seg3.events), 0)
        self.assertEqual(len(seg3.epochs), 0)
        self.assertEqual(len(seg3.eventarrays), 3)
        self.assertEqual(len(seg3.epocharrays), 2)

    def test_block(self):
        objects = [Block]

        res = generate_from_supported_objects(objects)

        self.assertTrue(isinstance(res, Block))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.segments), 0)

    def test_block_segment(self):
        objects = [Segment, Block]

        res = generate_from_supported_objects(objects)

        self.assertTrue(isinstance(res, Block))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.segments), 3)
        seg1, seg2, seg3 = res.segments

        self.assertEqual(len(seg1.analogsignals), 0)
        self.assertEqual(len(seg1.analogsignalarrays), 0)
        self.assertEqual(len(seg1.irregularlysampledsignals), 0)
        self.assertEqual(len(seg1.spiketrains), 0)
        self.assertEqual(len(seg1.spikes), 0)
        self.assertEqual(len(seg1.events), 0)
        self.assertEqual(len(seg1.epochs), 0)
        self.assertEqual(len(seg1.eventarrays), 0)
        self.assertEqual(len(seg1.epocharrays), 0)

        self.assertEqual(len(seg2.analogsignals), 0)
        self.assertEqual(len(seg2.analogsignalarrays), 0)
        self.assertEqual(len(seg2.irregularlysampledsignals), 0)
        self.assertEqual(len(seg2.spiketrains), 0)
        self.assertEqual(len(seg2.spikes), 0)
        self.assertEqual(len(seg2.events), 0)
        self.assertEqual(len(seg2.epochs), 0)
        self.assertEqual(len(seg2.eventarrays), 0)
        self.assertEqual(len(seg2.epocharrays), 0)

        self.assertEqual(len(seg3.analogsignals), 0)
        self.assertEqual(len(seg3.analogsignalarrays), 0)
        self.assertEqual(len(seg3.irregularlysampledsignals), 0)
        self.assertEqual(len(seg3.spiketrains), 0)
        self.assertEqual(len(seg3.spikes), 0)
        self.assertEqual(len(seg3.events), 0)
        self.assertEqual(len(seg3.epochs), 0)
        self.assertEqual(len(seg3.eventarrays), 0)
        self.assertEqual(len(seg3.epocharrays), 0)

    def test_segment(self):
        objects = [Segment]

        res = generate_from_supported_objects(objects)

        self.assertTrue(isinstance(res, Segment))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.analogsignals), 0)
        self.assertEqual(len(res.analogsignalarrays), 0)
        self.assertEqual(len(res.irregularlysampledsignals), 0)
        self.assertEqual(len(res.spiketrains), 0)
        self.assertEqual(len(res.spikes), 0)
        self.assertEqual(len(res.events), 0)
        self.assertEqual(len(res.epochs), 0)
        self.assertEqual(len(res.eventarrays), 0)
        self.assertEqual(len(res.epocharrays), 0)

    def test_all_without_block(self):
        objects = [Segment,
                   RecordingChannelGroup, RecordingChannel, Unit,
                   AnalogSignal, AnalogSignalArray,
                   IrregularlySampledSignal, SpikeTrain,
                   Event, Epoch, Spike,
                   EventArray, EpochArray]

        res = generate_from_supported_objects(objects)

        self.assertTrue(isinstance(res, Segment))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.analogsignals), 4)
        self.assertEqual(len(res.analogsignalarrays), 0)
        self.assertEqual(len(res.irregularlysampledsignals), 0)
        self.assertEqual(len(res.spiketrains), 6)
        self.assertEqual(len(res.spikes), 0)
        self.assertEqual(len(res.events), 0)
        self.assertEqual(len(res.epochs), 0)
        self.assertEqual(len(res.eventarrays), 3)
        self.assertEqual(len(res.epocharrays), 2)

    def test_all_without_segment(self):
        objects = [Block,
                   RecordingChannelGroup, RecordingChannel, Unit,
                   AnalogSignal, AnalogSignalArray,
                   IrregularlySampledSignal, SpikeTrain,
                   Event, Epoch, Spike,
                   EventArray, EpochArray]

        res = generate_from_supported_objects(supported_objects=objects)

        self.assertTrue(isinstance(res, Block))
        assert_neo_object_is_compliant(res)

        self.assertEqual(len(res.segments), 0)

class Test__get_fake_value(unittest.TestCase):
    def setUp(self):
        np.random.seed(0)

    def test__t_start(self):
        name = 't_start'
        datatype = pq.Quantity
        targ = 0.0 * pq.millisecond

        res = get_fake_value(name, datatype)
        self.assertTrue(isinstance(res, pq.Quantity))
        self.assertEqual(res.units, pq.millisecond)
        assert_arrays_equal(targ, res)

        self.assertRaises(ValueError, get_fake_value, name, datatype, dim=1)
        self.assertRaises(ValueError, get_fake_value, name, np.ndarray)

    def test__t_stop(self):
        name = 't_stop'
        datatype = pq.Quantity
        targ = 1.0 * pq.millisecond

        res = get_fake_value(name, datatype)
        self.assertTrue(isinstance(res, pq.Quantity))
        self.assertEqual(res.units, pq.millisecond)
        assert_arrays_equal(targ, res)

        self.assertRaises(ValueError, get_fake_value, name, datatype, dim=1)
        self.assertRaises(ValueError, get_fake_value, name, np.ndarray)

    def test__sampling_rate(self):
        name = 'sampling_rate'
        datatype = pq.Quantity
        targ = 10000.0 * pq.Hz

        res = get_fake_value(name, datatype)
        self.assertTrue(isinstance(res, pq.Quantity))
        self.assertEqual(res.units, pq.Hz)
        assert_arrays_equal(targ, res)

        self.assertRaises(ValueError, get_fake_value, name, datatype, dim=1)
        self.assertRaises(ValueError, get_fake_value, name, np.ndarray)

    def test__str(self):
        name = 'test__str'
        datatype = str
        targ = str(np.random.randint(100000))

        res = get_fake_value(name, datatype, seed=0)
        self.assertTrue(isinstance(res, str))
        self.assertEqual(targ, res)

    def test__name(self):
        name = 'name'
        datatype = str
        obj = 'Block'
        targ = 'Block'+str(np.random.randint(100000))

        res = get_fake_value(name, datatype, seed=0, obj=obj)
        self.assertTrue(isinstance(res, str))
        self.assertEqual(targ, res)

        self.assertRaises(ValueError, get_fake_value, name, datatype, dim=1)
        self.assertRaises(ValueError, get_fake_value, name, np.ndarray)

    def test__description(self):
        name = 'description'
        datatype = str
        obj = Segment
        targ = 'test Segment '+str(np.random.randint(100000))

        res = get_fake_value(name, datatype, seed=0, obj=obj)
        self.assertTrue(isinstance(res, str))
        self.assertEqual(targ, res)

        self.assertRaises(ValueError, get_fake_value, name, datatype, dim=1)
        self.assertRaises(ValueError, get_fake_value, name, np.ndarray)

    def test__file_origin(self):
        name = 'file_origin'
        datatype = str
        targ = 'test_file.txt'

        res = get_fake_value(name, datatype, seed=0)
        self.assertTrue(isinstance(res, str))
        self.assertEqual(targ, res)

        self.assertRaises(ValueError, get_fake_value, name, datatype, dim=1)
        self.assertRaises(ValueError, get_fake_value, name, np.ndarray)

    def test__int(self):
        name = 'test__int'
        datatype = int
        targ = np.random.randint(100)

        res = get_fake_value(name, datatype, seed=0)
        self.assertTrue(isinstance(res, int))
        self.assertEqual(targ, res)

    def test__float(self):
        name = 'test__float'
        datatype = float
        targ = 1000. * np.random.random()

        res = get_fake_value(name, datatype, seed=0)
        self.assertTrue(isinstance(res, float))
        self.assertEqual(targ, res)

    def test__datetime(self):
        name = 'test__datetime'
        datatype = datetime
        targ = datetime.fromtimestamp(1000000000*np.random.random())

        res = get_fake_value(name, datatype, seed=0)
        self.assertTrue(isinstance(res, datetime))
        self.assertEqual(res, targ)

    def test__quantity(self):
        name = 'test__quantity'
        datatype = pq.Quantity
        dim = 2

        size = []
        units = np.random.choice(['nA', 'mA', 'A', 'mV', 'V'])
        for i in range(int(dim)):
            size.append(np.random.randint(5) + 1)
        targ = pq.Quantity(np.random.random(size)*1000, units=units)

        res = get_fake_value(name, datatype, dim=dim, seed=0)
        self.assertTrue(isinstance(res, pq.Quantity))
        self.assertEqual(res.units, getattr(pq, units))
        assert_arrays_equal(targ, res)

    def test__quantity_force_units(self):
        name = 'test__quantity'
        datatype = np.ndarray
        dim = 2
        units = pq.ohm

        size = []
        for i in range(int(dim)):
            size.append(np.random.randint(5) + 1)
        targ = pq.Quantity(np.random.random(size)*1000, units=units)

        res = get_fake_value(name, datatype, dim=dim, seed=0, units=units)
        self.assertTrue(isinstance(res, np.ndarray))
        assert_arrays_equal(targ, res)

    def test__ndarray(self):
        name = 'test__ndarray'
        datatype = np.ndarray
        dim = 2

        size = []
        for i in range(int(dim)):
            size.append(np.random.randint(5) + 1)
        targ = np.random.random(size)*1000

        res = get_fake_value(name, datatype, dim=dim, seed=0)
        self.assertTrue(isinstance(res, np.ndarray))
        assert_arrays_equal(targ, res)

    def test__list(self):
        name = 'test__list'
        datatype = list
        dim = 2

        size = []
        for i in range(int(dim)):
            size.append(np.random.randint(5) + 1)
        targ = (np.random.random(size)*1000).tolist()

        res = get_fake_value(name, datatype, dim=dim, seed=0)
        self.assertTrue(isinstance(res, list))
        self.assertEqual(targ, res)

    def test__other_valueerror(self):
        name = 'test__other_fail'
        datatype = set([1, 2, 3, 4])

        self.assertRaises(ValueError, get_fake_value, name, datatype)

class Test__get_fake_values(unittest.TestCase):
    def setUp(self):
        np.random.seed(0)
        self.annotations = dict([(str(x), TEST_ANNOTATIONS[x]) for x in
                                 range(len(TEST_ANNOTATIONS))])
        self.annotations['seed'] = 0

    def subcheck__get_fake_values(self, cls):
        res1 = get_fake_values(cls, annotate=False, seed=0)
        res2 = get_fake_values(cls, annotate=True, seed=0)

        if hasattr(cls, 'lower'):
            cls = class_by_name[cls]

        attrs = cls._necessary_attrs + cls._recommended_attrs

        attrnames = [attr[0] for attr in attrs]
        attrtypes = [attr[1] for attr in attrs]

        attritems = zip(attrnames, attrtypes)

        attrannnames = attrnames + list(self.annotations.keys())

        self.assertEqual(sorted(attrnames), sorted(res1.keys()))
        self.assertEqual(sorted(attrannnames), sorted(res2.keys()))

        items11 = [(name, type(value)) for name, value in res1.items()]
        self.assertEqual(sorted(attritems), sorted(items11))
        for name, value in res1.items():
            try:
                self.assertEqual(res2[name], value)
            except ValueError:
                assert_arrays_equal(res2[name], value)

        for name, value in self.annotations.items():
            self.assertFalse(name in res1)
            self.assertEqual(res2[name], value)

        for attr in attrs:
            name = attr[0]
            if len(attr) < 3:
                continue

            dim = attr[2]
            self.assertEqual(dim, res1[name].ndim)
            self.assertEqual(dim, res2[name].ndim)

            if len(attr) < 4:
                continue

            dtype = attr[3]
            self.assertEqual(dtype.kind, res1[name].dtype.kind)
            self.assertEqual(dtype.kind, res2[name].dtype.kind)

    def check__get_fake_values(self, cls):
        self.subcheck__get_fake_values(cls)
        self.subcheck__get_fake_values(cls.__name__)

    def test__analogsignal(self):
        self.check__get_fake_values(AnalogSignal)

    def test__analogsignalarray(self):
        self.check__get_fake_values(AnalogSignalArray)

    def test__block(self):
        self.check__get_fake_values(Block)

    def test__epoch(self):
        self.check__get_fake_values(Epoch)

    def test__epocharray(self):
        self.check__get_fake_values(EpochArray)

    def test__event(self):
        self.check__get_fake_values(Event)

    def test__eventarray(self):
        self.check__get_fake_values(EventArray)

    def test__irregularlysampledsignal(self):
        self.check__get_fake_values(IrregularlySampledSignal)

    def test__recordingchannel(self):
        self.check__get_fake_values(RecordingChannel)

    def test__recordingchannelgroup(self):
        self.check__get_fake_values(RecordingChannelGroup)

    def test__segment(self):
        self.check__get_fake_values(Segment)

    def test__spike(self):
        self.check__get_fake_values(Spike)

    def test__spiketrain(self):
        self.check__get_fake_values(SpikeTrain)

    def test__unit(self):
        self.check__get_fake_values(Unit)

class Test__generate_datasets(unittest.TestCase):
    def setUp(self):
        self.annotations = dict([(str(x), TEST_ANNOTATIONS[x]) for x in
                                 range(len(TEST_ANNOTATIONS))])

    def check__generate_datasets(self, cls):
        clsname = cls.__name__

        self.subcheck__generate_datasets(cls, cascade=True)
        self.subcheck__generate_datasets(cls, cascade=True, seed=0)
        self.subcheck__generate_datasets(cls, cascade=False)
        self.subcheck__generate_datasets(cls, cascade=False, seed=0)
        self.subcheck__generate_datasets(clsname, cascade=True)
        self.subcheck__generate_datasets(clsname, cascade=True, seed=0)
        self.subcheck__generate_datasets(clsname, cascade=False)
        self.subcheck__generate_datasets(clsname, cascade=False, seed=0)

    def subcheck__generate_datasets(self, cls, cascade, seed=None):
        self.annotations['seed'] = seed

        if seed is None:
            res = fake_neo(obj_type=cls, cascade=cascade)
        else:
            res = fake_neo(obj_type=cls, cascade=cascade, seed=seed)

        if not hasattr(cls, 'lower'):
            self.assertTrue(isinstance(res, cls))
        else:
            self.assertEqual(res.__class__.__name__, cls)

        assert_neo_object_is_compliant(res)
        self.assertEqual(res.annotations, self.annotations)

        resattr = get_fake_values(cls, annotate=False, seed=0)
        if seed is not None:
            for name, value in resattr.items():
                if name in ['channel_names',
                            'channel_indexes',
                            'channel_index']:
                    continue
                try:
                    try:
                        resvalue = getattr(res, name)
                    except AttributeError:
                        if name == 'signal':
                            continue
                        raise
                    try:
                        self.assertEqual(resvalue, value)
                    except ValueError:
                        assert_arrays_equal(resvalue, value)
                except BaseException as exc:
                    exc.args += ('from %s' % name,)
                    raise

        if not getattr(res, '_child_objects', ()):
            pass
        elif not cascade:
            self.assertEqual(res.children, ())
        else:
            self.assertNotEqual(res.children, ())

        if cls in ['RecordingChannelGroup', RecordingChannelGroup]:
            for i, rchan in enumerate(res.recordingchannels):
                self.assertEqual(rchan.name, res.channel_names[i].astype(str))
                self.assertEqual(rchan.index, res.channel_indexes[i])
            for i, unit in enumerate(res.units):
                for sigarr in res.analogsignalarrays:
                    self.assertEqual(unit.channel_indexes[0],
                                     sigarr.channel_index[i])

    def test__analogsignal(self):
        self.check__generate_datasets(AnalogSignal)

    def test__analogsignalarray(self):
        self.check__generate_datasets(AnalogSignal)

    def test__block(self):
        self.check__generate_datasets(AnalogSignalArray)

    def test__epoch(self):
        self.check__generate_datasets(Epoch)

    def test__epocharray(self):
        self.check__generate_datasets(EpochArray)

    def test__event(self):
        self.check__generate_datasets(Event)

    def test__eventarray(self):
        self.check__generate_datasets(EventArray)

    def test__irregularlysampledsignal(self):
        self.check__generate_datasets(IrregularlySampledSignal)

    def test__recordingchannel(self):
        self.check__generate_datasets(RecordingChannel)

    def test__recordingchannelgroup(self):
        self.check__generate_datasets(RecordingChannelGroup)

    def test__segment(self):
        self.check__generate_datasets(Segment)

    def test__spike(self):
        self.check__generate_datasets(Spike)

    def test__spiketrain(self):
        self.check__generate_datasets(SpikeTrain)

    def test__unit(self):
        self.check__generate_datasets(Unit)

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Py React Lab</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">

Kinetic JS on React


text:
// -*- C++ -*-

//=============================================================================
/**
 *  @file   FTEC_SupplierAdmin.h
 *
 *  $Id: FTEC_SupplierAdmin.h 935 2008-12-10 21:47:27Z mitza $
 *
 *  @author Huang-Ming Huang <hh1@cse.wustl.edu>
 */
//=============================================================================

#ifndef TAO_FTEC_SUPPLIERADMIN_H
#define TAO_FTEC_SUPPLIERADMIN_H
#include /**/ "ace/pre.h"

#include "orbsvcs/FtRtEvent/EventChannel/FTEC_ProxyConsumer.h"
#include "orbsvcs/FtRtEvent/EventChannel/FT_ProxyAdmin_T.h"
#include "orbsvcs/FtRtEvent/EventChannel/ProxyConsumerStateWorker.h"

#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */

#include "orbsvcs/Event/EC_SupplierAdmin.h"

TAO_BEGIN_VERSIONED_NAMESPACE_DECL

class TAO_FTEC_Event_Channel_Impl;

namespace FtRtecEventChannelAdmin {
  struct SupplierAdminState;
}
/**
 * @class TAO_FTEC_SupplierAdmin
 *
 * @brief Implement the RtecEventChannelAdmin::SupplierAdmin interface.
 *
 *
 */
class TAO_FTEC_SupplierAdmin
  : public TAO_EC_SupplierAdmin
  , public FT_ProxyAdmin<TAO_FTEC_SupplierAdmin,
                         TAO_FTEC_ProxyPushConsumer,
             RtecEventChannelAdmin::ProxyPushConsumer,
             FtRtecEventChannelAdmin::SupplierAdminState>
{
public:

  static const FtRtecEventChannelAdmin::OperationType OBTAIN_ID;

  typedef FT_ProxyAdmin<TAO_FTEC_SupplierAdmin,
                         TAO_FTEC_ProxyPushConsumer,
             RtecEventChannelAdmin::ProxyPushConsumer,
             FtRtecEventChannelAdmin::SupplierAdminState>
          FT_Aspect;

  typedef ProxyConsumerStateWorker  StateWorker;

  /// constructor...
  TAO_FTEC_SupplierAdmin (TAO_EC_Event_Channel_Base* event_channel);

  /// destructor...
  virtual ~TAO_FTEC_SupplierAdmin (void);

  // = The RtecEventChannelAdmin::SupplierAdmin methods...
  virtual RtecEventChannelAdmin::ProxyPushConsumer_ptr
      obtain_push_consumer (void);

  void disconnect(RtecEventChannelAdmin::ProxyPushConsumer_ptr obj);
};

TAO_END_VERSIONED_NAMESPACE_DECL

#include /**/ "ace/post.h"
#endif /* TAO_FTEC_SUPPLIERADMIN_H */


text:
package com.flydenver.bagrouter.routing;

/**
 * General edge for a graph. Edge here is defined by the
 * connection between two nodes.
 */
public interface Edge<T> {

	/**
	 * Getter for fist node (or starting node).
	 */
	Node<T> getFirstNode();

	/**
	 * Getter for second node (or ended node).
	 */
	Node<T> getSecondNode();

	/**
	 * Using either the first or second node, get the other node.
	 * @param thisNode from node
	 * @return other node
	 */
	Node<T> getOtherNode( Node<T> thisNode );

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Operation</title>
<meta name="date" content="2015-05-12">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

service.auxiliary

Class Operation

java.lang.Object

service.auxiliary.Operation

All Implemented Interfaces:

java.io.Serializable

public class Operation
extends java.lang.Object
implements java.io.Serializable

Definition of a service operation

Author:

Yifan Ruan (ry222ad@student.lnu.se)

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

Operation(java.lang.String opName,
         java.lang.Class<?>[] paramTypes,
         java.lang.String returnType)

Constructor

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object obj)

Override the "equals" method

double
getOpCost()

Return the operation cost

java.lang.String
getOpName()

Return the operation name

java.lang.Class<?>[]
getParamTypes()

Return the type array of parameters

java.lang.String
getReturnType()

Return the return type of the operation

void
setOpCost(double opCost)

Set the operation cost

java.lang.String
toString()

Override the "toString" method

Methods inherited from class java.lang.Object

getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

Operation

public Operation(java.lang.String opName,
                 java.lang.Class<?>[] paramTypes,
                 java.lang.String returnType)

Constructor

Parameters:

opName - the operation name

paramTypes - the type array of parameters

returnType - the return type

Method Detail

getOpName

public java.lang.String getOpName()

Return the operation name

Returns:

the operation name

getParamTypes

public java.lang.Class<?>[] getParamTypes()

Return the type array of parameters

Returns:

the paramTypes

getReturnType

public java.lang.String getReturnType()

Return the return type of the operation

Returns:

the return type

getOpCost

public double getOpCost()

Return the operation cost

Returns:

the operation cost

setOpCost

public void setOpCost(double opCost)

Set the operation cost

Parameters:

opCost - the new operation cost

equals

public boolean equals(java.lang.Object obj)

Override the "equals" method

Overrides:

equals in class java.lang.Object

toString

public java.lang.String toString()

Override the "toString" method

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
@class DVTBorderedView, DVTLozengeTextField, DVTObservingToken, DVTOutlineView, DVTScopeBarButton, DVTSearchField, IDETestReportBaselineUpdateController, IDETestReportBatchBaselineUpdateWindow, IDETestReportTestRunFetcher, NSArray, NSButton, NSDictionary, NSMapTable, NSMutableArray, NSMutableIndexSet, NSOperationQueue, NSPopover, NSScrollView, NSString, NSURL, NSView;

@interface IDETestReportViewController : IDEViewController <NSOutlineViewDelegate, NSOutlineViewDataSource, IDETestsInTestableObserver, NSPopoverDelegate, QLPreviewPanelDataSource>
{
    NSOperationQueue *testPlaceholderQueryQueue;
    IDETestReportBaselineUpdateController *_baselineUpdatesController;
    unsigned long long _countOfTestablesToUpdate;
    unsigned long long _countOfTestManagerTestables;
    IDETestReportTestRunFetcher *_testRunFetcher;
    IDETestReportBatchBaselineUpdateWindow *_updateWindow;
    unsigned long long _selectedBaselineRecordBehavior;
    BOOL _prefetchingLazyLoadedTestRuns;
    NSMapTable *_filteredTestsAndGroupItems;
    NSPopover *_setBaselinePopover;
    DVTObservingToken *_controllerContentViewLayoutObservingToken;
    BOOL _readyToReloadView;
    DVTObservingToken *_accessoryViewAlertOptionsToken;
    id  _clientTrackingToken;
    NSMutableArray *_activitiesViewCurrentSelectedDocumentLocationObservers;
    NSMutableArray *_currentlyExpandedTestItemIdentifiers;
    NSMutableArray *_testRunPickerRows;
    NSMapTable *_testRunPickerRowsAndSelectedTestRun;
    NSMutableArray *_remoteDownloadHelpers;
    NSURL *_quickLookURL;
    NSView *_quickLookPanelOriginView;
    NSMutableIndexSet *_multilineAssertionRowIndexes;
    NSMutableArray *_assertionOutlineObjects;
    id _scrollViewBoundsDidChangeObserver;
    id _windowDidBecomeMainObserver;
    struct CGRect _masterCellViewXIBFrame;
    struct CGRect _masterCellViewTextFieldFrame;
    struct CGRect _masterCellViewButtonFrame;
    NSMutableArray *_filteredGroupsWithNamesMatchingFilterPredicate;
    BOOL _failingOnly;
    BOOL _passedOnly;
    BOOL _failedExpectedOnly;
    BOOL _perfOnly;
    id  _rootObject;
    dispatch_block_t _testSelectedCallback;
    dispatch_block_t _selectedActivityScreenShot;
    DVTBorderedView *_filterBarBorderedView;
    DVTSearchField *_filterField;
    DVTLozengeTextField *_lozengeTextField;
    DVTScopeBarButton *_scopeBarAllButton;
    DVTScopeBarButton *_scopeBarPassedButton;
    DVTScopeBarButton *_scopeBarFailedButton;
    DVTScopeBarButton *_scopeBarUnitAndPerfTestsButton;
    DVTScopeBarButton *_scopeBarPerformanceTestsButton;
    NSButton *_setBaselinesButton;
    DVTOutlineView *_testsOutlineView;
    NSScrollView *_testsScrollView;
    NSArray *_deviceColumns;
    NSArray *_perfMetricColumns;
    NSArray *_filteredTests;
    NSArray *_outlineViewRootItems;
    NSArray *_filteredOutlineViewRootItems;
    NSArray *_perfTestMetricNames;
    NSDictionary *_fetchedTests;
    NSDictionary *_testItemsByIdentifier;
}

+ (BOOL)alwayShowQuickLookButton;
+ (void)initialize;
@property(retain, nonatomic) NSDictionary *testItemsByIdentifier; // @synthesize testItemsByIdentifier=_testItemsByIdentifier;
@property(copy) NSDictionary *fetchedTests; // @synthesize fetchedTests=_fetchedTests;
@property(copy) NSArray *perfTestMetricNames; // @synthesize perfTestMetricNames=_perfTestMetricNames;
@property BOOL perfOnly; // @synthesize perfOnly=_perfOnly;
@property BOOL failedExpectedOnly; // @synthesize failedExpectedOnly=_failedExpectedOnly;
@property BOOL passedOnly; // @synthesize passedOnly=_passedOnly;
@property BOOL failingOnly; // @synthesize failingOnly=_failingOnly;
@property(copy) NSArray *filteredOutlineViewRootItems; // @synthesize filteredOutlineViewRootItems=_filteredOutlineViewRootItems;
@property(copy) NSArray *outlineViewRootItems; // @synthesize outlineViewRootItems=_outlineViewRootItems;
@property(copy) NSArray *filteredTests; // @synthesize filteredTests=_filteredTests;
@property(retain) NSArray *perfMetricColumns; // @synthesize perfMetricColumns=_perfMetricColumns;
@property(retain) NSArray *deviceColumns; // @synthesize deviceColumns=_deviceColumns;
@property __weak NSScrollView *testsScrollView; // @synthesize testsScrollView=_testsScrollView;
@property __weak DVTOutlineView *testsOutlineView; // @synthesize testsOutlineView=_testsOutlineView;
@property __weak NSButton *setBaselinesButton; // @synthesize setBaselinesButton=_setBaselinesButton;
@property __weak DVTScopeBarButton *scopeBarPerformanceTestsButton; // @synthesize scopeBarPerformanceTestsButton=_scopeBarPerformanceTestsButton;
@property __weak DVTScopeBarButton *scopeBarUnitAndPerfTestsButton; // @synthesize scopeBarUnitAndPerfTestsButton=_scopeBarUnitAndPerfTestsButton;
@property __weak DVTScopeBarButton *scopeBarFailedButton; // @synthesize scopeBarFailedButton=_scopeBarFailedButton;
@property __weak DVTScopeBarButton *scopeBarPassedButton; // @synthesize scopeBarPassedButton=_scopeBarPassedButton;
@property __weak DVTScopeBarButton *scopeBarAllButton; // @synthesize scopeBarAllButton=_scopeBarAllButton;
@property __weak DVTLozengeTextField *lozengeTextField; // @synthesize lozengeTextField=_lozengeTextField;
@property __weak DVTSearchField *filterField; // @synthesize filterField=_filterField;
@property __weak DVTBorderedView *filterBarBorderedView; // @synthesize filterBarBorderedView=_filterBarBorderedView;
@property(readonly, nonatomic) NSArray *currentlyExpandedTestItemIdentifiers; // @synthesize currentlyExpandedTestItemIdentifiers=_currentlyExpandedTestItemIdentifiers;
@property(copy, nonatomic) dispatch_block_t selectedActivityScreenShot; // @synthesize selectedActivityScreenShot=_selectedActivityScreenShot;
@property(copy, nonatomic) dispatch_block_t testSelectedCallback; // @synthesize testSelectedCallback=_testSelectedCallback;
@property(retain, nonatomic) id  rootObject; // @synthesize rootObject=_rootObject;
- (struct CGRect)previewPanel:(id)arg1 sourceFrameOnScreenForPreviewItem:(id)arg2;
- (void)endPreviewPanelControl:(id)arg1;
- (void)beginPreviewPanelControl:(id)arg1;
- (BOOL)acceptsPreviewPanelControl:(id)arg1;
- (id)previewPanel:(id)arg1 previewItemAtIndex:(long long)arg2;
- (long long)numberOfPreviewItemsInPreviewPanel:(id)arg1;
- (void)quickLookRow:(id)arg1;
- (id)parentTestItemOfActivity:(id)arg1;
- (void)configureMasterCellView:(id)arg1 activity:(id)arg2 isMasterActivity:(BOOL)arg3 isFirstActivity:(BOOL)arg4 startTime:(id)arg5;
- (void)selectItemWithIdentifier:(id)arg1;
- (void)expandItemsWithIdentifiers:(id)arg1;
- (void)updateBaselineForPerfMetric:(id)arg1 inTestRun:(id)arg2 newBaseline:(double)arg3 newAllowedSTD:(id)arg4;
- (id)assertionsAttributedStringForTestFailures:(id)arg1 noBaselines:(id)arg2;
- (id)assertionsInTestRun:(id)arg1;
- (id)noBaselineWarningsInTestRun:(id)arg1;
- (BOOL)testRunHasMissingBaseline:(id)arg1;
- (void)showTestAssertionsForTestRun:(id)arg1 inTest:(id)arg2 button:(id)arg3;
- (void)_showBaselinePopoverForTest:(id)arg1 test:(id)arg2 relativeTo:(id)arg3;
- (void)popoverDidClose:(id)arg1;
- (void)outlineViewItemDidCollapse:(id)arg1;
- (void)outlineViewItemDidExpand:(id)arg1;
- (void)outlineViewItemWillCollapse:(id)arg1;
- (void)outlineViewItemWillExpand:(id)arg1;
- (id)outlineView:(id)arg1 viewForTableColumn:(id)arg2 item:(id)arg3;
- (void)configureAndSizeMultilineActivitiesTableCellView:(id)arg1 itemLevel:(unsigned long long)arg2;
- (void)outlineViewColumnDidResize:(id)arg1;
- (void)showResultsForTestRun:(id)arg1;
- (double)outlineView:(id)arg1 heightOfRowByItem:(id)arg2;
- (id)combinedAssertionsStringForFailureSummaries:(id)arg1;
- (struct CGSize)requiredSizeForAssertion:(id)arg1 itemLevel:(unsigned long long)arg2;
- (id)attributedStringForTestName:(id)arg1 parentGroupName:(id)arg2;
- (void)copy:(id)arg1;
- (id)outlineView:(id)arg1 rowViewForItem:(id)arg2;
- (void)outlineView:(id)arg1 didRemoveRowView:(id)arg2 forRow:(long long)arg3;
- (void)outlineViewSelectionDidChange:(id)arg1;
- (BOOL)outlineView:(id)arg1 shouldSelectItem:(id)arg2;
- (BOOL)outlineView:(id)arg1 shouldShowOutlineCellForItem:(id)arg2;
- (BOOL)outlineView:(id)arg1 isGroupItem:(id)arg2;
- (BOOL)itemIsAssertionFailure:(id)arg1;
- (id)outlineView:(id)arg1 child:(long long)arg2 ofItem:(id)arg3;
- (BOOL)outlineView:(id)arg1 isItemExpandable:(id)arg2;
- (long long)outlineView:(id)arg1 numberOfChildrenOfItem:(id)arg2;
- (void)testHasAssertions:(id)arg1 completionBlock:(dispatch_block_t)arg2;
- (void)showTestForClassName:(id)arg1 methodName:(id)arg2;
- (void)filterFieldAction:(id)arg1;
- (void)reloadAndFilterOutline;
- (id)filteredTestsRespectingScopeFiltersInTestGroup:(id)arg1 withFilterString:(id)arg2;
- (void)testablesChanged:(id)arg1;
- (void)allTestablesChanged;
- (void)testsChanged:(id)arg1;
- (void)observePerfTestGroupTestables;
- (void)setBaselinesAction:(id)arg1;
- (BOOL)_testsProvideBlueprintInfo;
- (void)scopeBarUnitAndPerfTests:(id)arg1;
- (void)scopeBarPerformance:(id)arg1;
- (void)scopeBarFailed:(id)arg1;
- (void)scopeBarPassed:(id)arg1;
- (void)scopeBarAll:(id)arg1;
- (void)scopeBarChanged;
- (void)commitScopeBarState;
- (void)restoreScopeBarState;
- (void)prefetchLazyLoadedTestRuns;
- (void)reloadAndExpandOutlineView;
- (id)allPerfTestGroups;
- (id)testClassesWithScopeBarFiltering;
- (void)primitiveInvalidate;
- (void)loadView;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly, nonatomic) NSMutableArray *mutableCurrentlyExpandedTestItemIdentifiers; // @dynamic mutableCurrentlyExpandedTestItemIdentifiers;
@property(readonly) Class superclass;

@end


text:
package com.tekihub.kameleon.watchtheme.usage.tasks;

import android.annotation.TargetApi;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.os.Build;
import com.tekihub.kameleon.watchtheme.di.WatchThemeScope;
import javax.inject.Inject;

@WatchThemeScope public class CheckForegroundAppTask21Func extends CheckForegroundAppTask {
    private static final String USAGE_STATS_SERVICE = "usagestats";

    @Inject public CheckForegroundAppTask21Func(Context context) {
        super(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public String call(Long interval) {
        final UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(USAGE_STATS_SERVICE);
        long current = System.currentTimeMillis();
        UsageEvents events = usageStatsManager.queryEvents(current - 2000, current);
        UsageEvents.Event event = new UsageEvents.Event();
        String packageName = "";
        while (events.hasNextEvent()) {
            events.getNextEvent(event);
            if (event.getEventType() == UsageEvents.Event.MOVE_TO_FOREGROUND) {
                packageName = event.getPackageName();
            }
        }

        return packageName;
    }
}


text:
package com.cloudera.flume.reporter.charts.google;

import java.util.List;

import com.cloudera.flume.reporter.history.TimelineChartGen;
import com.cloudera.util.Pair;

/**
 * This generates a google charts html tag that generates a line graph based on
 * a list of <timestamp,count>.
 *
 * The data set's max y value is set to hover around 2/3 of the height of the
 * graph.
 *
 * Go here for the details behind the magic incantations.
 * http://code.google.com/apis/chart/
 */
class GoogleTimelineChartGen extends TimelineChartGen<Long> {

  final String title;

  final int height, width;

  public GoogleTimelineChartGen(String title, int height, int width) {
    this.title = title;
    this.height = height;
    this.width = width;
  }

  public GoogleTimelineChartGen(String title) {
    this(title, 300, 300);
  }

  public GoogleTimelineChartGen() {
    this(null, 300, 300);
  }

  private String size() {
    // chs == chart size
    return "chs=" + width + "x" + height;
  }

  @Override
  public String generate(List<Pair<Long, Long>> history) {

    String title = "";
    if (this.title != null) {
      // chtt is chart title
      // TODO (jon) check title string; need to escape spaces with '+').
      title = "&chtt=" + this.title;
    }
    String data = timeline(history);

    return "<img src=\"" + GoogleHistogramChartGen.BASE_URL + size() + title + data
        + "\" />";
  }

  // Text encoding with data scaling
  // Left element is the timestamp, and the right element is a count value.
  // If there are >10 entries, we use a line chart, otherwises a bar graph
  //
  // TODO (jon) Right now we ignore the timestamp (assuming each time step is
  // equal)
  private String timeline(List<Pair<Long, Long>> h) {
    StringBuilder data = new StringBuilder();
    long max = 0;
    long sum = 0;
    long cnt = h.size();

    if (cnt == 0) {
      return ""; // No Data!
    }

    for (Pair<Long, Long> p : h) {
      max = p.getRight() > max ? p.getRight() : max;
      cnt++;
      sum += p.getRight();
      if (data.length() == 0) {
        data.append(p.getRight());
      } else {
        data.append("," + p.getRight());
      }
    }

    // truncate y axis at avg
    // make max hover around 2/3s of the way up the chart.
    // chds == chart data set limits
    String limits = "&chds=0," + (max * 3 / 2); // chds = chart dimensions

    // add axis, last entry doesn't have a '|'
    // chxt == chart axes == y is left, x is bottom.
    // chxl == chart axis labels
    String axis = "&chxt=y,x&chxl=0:|0|" + (max * 3 / 2) + "|1:|0|" + cnt;

    // cht=bvg == chart type is vertical bar graph
    String charttype = "&cht=bvg";

    if (cnt > 10) {
      // cht=lc == chart type is linechart
      charttype = "&cht=lc";
    }

    // chd = chart data string
    return charttype + "&chd=t:" + data.toString() + limits + axis;
  }

}


text:
package eu.ehealth.controllers.externalservices;

import java.rmi.RemoteException;
import org.zkoss.util.resource.Labels;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;
import org.zkoss.zul.Button;
import eu.ehealth.SystemDictionary;
import eu.ehealth.ws_client.StorageComponentImpl;
import eu.ehealth.ws_client.xsd.ExternalService;
import eu.ehealth.ws_client.xsd.OperationResult;

/**
 *
 *
 * @author
 * @date 22/04/2014.
 *
 */
public class ExternalServicesIndexController extends Window
{

	private static final long serialVersionUID = -8597729277696823899L;
	public Window servicePopup;

	/**
	 *
	 * @throws InterruptedException
	 */
	public void createService() throws InterruptedException
	{
		servicePopup = (Window) Executions.createComponents("form.zul", this, null);
		((Button) servicePopup.getFellow("savebutton")).setVisible(true);
		String title = Labels.getLabel("extsrv.new");
		servicePopup.setTitle(title);
		servicePopup.setVisible(true);
		servicePopup.doModal();
	}

	/**
	 *
	 * @param srvid
	 * @throws RemoteException
	 * @throws InterruptedException
	 */
	public void modifyService(String srvid) throws RemoteException, InterruptedException
	{
		StorageComponentImpl proxy = new StorageComponentImpl();
		ExternalService defserv = null;
		String userid = (String) Sessions.getCurrent().getAttribute("userid");
		ExternalService[] services = proxy.getAllExternalServicesArr(userid);
		for (int i = 0; i < services.length; i++)
		{
			if (services[i].getID().equals(srvid))
			{
				defserv = services[i];
				break;
			}
		}

		servicePopup = (Window) Executions.createComponents("form.zul", this, null);

		int selectedindex = 1;
		if (defserv.getType().equals(SystemDictionary.EXT_SERV_EXERCISES)) {
			selectedindex = 0;
		}
		((Listbox) servicePopup.getFellow("content_type")).setSelectedIndex(selectedindex);

		((Button) servicePopup.getFellow("cancelbutton")).setVisible(true);
		((Textbox) servicePopup.getFellow("srvidfield")).setValue(srvid);
		((Textbox) servicePopup.getFellow("srvdescfield")).setValue(defserv.getDescription());
		((Textbox) servicePopup.getFellow("srvuricfield")).setValue(defserv.getAddress());
		String title = Labels.getLabel("extsrv.update");
		servicePopup.setTitle(title);
		servicePopup.setVisible(true);
		servicePopup.doModal();
	}

	/**
	 *
	 * @param srvid
	 * @throws RemoteException
	 * @throws InterruptedException
	 */
	public void viewService(String srvid) throws RemoteException, InterruptedException
	{
		StorageComponentImpl proxy = new StorageComponentImpl();
		ExternalService defserv = null;
		String userid = (String) Sessions.getCurrent().getAttribute("userid");
		ExternalService[] services = proxy.getAllExternalServicesArr(userid);
		for (int i = 0; i < services.length; i++)
		{
			if (services[i].getID().equals(srvid))
			{
				defserv = services[i];
				break;
			}
		}
		servicePopup = (Window) Executions.createComponents("form.zul", this, null);

		int selectedindex = 1;
		if (defserv.getType().equals(SystemDictionary.EXT_SERV_EXERCISES)) {
			selectedindex = 0;
		}
		((Listbox) servicePopup.getFellow("content_type")).setSelectedIndex(selectedindex);
		((Listbox) servicePopup.getFellow("content_type")).setDisabled(true);

		((Button) servicePopup.getFellow("cancelbutton")).setVisible(false);
		((Button) servicePopup.getFellow("savebutton")).setVisible(false);
		((Textbox) servicePopup.getFellow("srvidfield")).setValue(srvid);
		((Textbox) servicePopup.getFellow("srvidfield")).setReadonly(true);
		((Textbox) servicePopup.getFellow("srvdescfield")).setValue(defserv.getDescription());
		((Textbox) servicePopup.getFellow("srvdescfield")).setReadonly(true);
		((Textbox) servicePopup.getFellow("srvuricfield")).setValue(defserv.getAddress());
		((Textbox) servicePopup.getFellow("srvuricfield")).setReadonly(true);
		String title = Labels.getLabel("common.view");
		servicePopup.setTitle(title);
		servicePopup.setVisible(true);
		servicePopup.doModal();
	}

	/**
	 *
	 * @param srvid
	 */
	public void delteService(String srvid)
	{
		StorageComponentImpl proxy = new StorageComponentImpl();
		String userid = (String) Sessions.getCurrent().getAttribute("userid");
		try
		{
			SystemDictionary.webguiLog("TRACE", "Deleting... ");
			OperationResult result = proxy.deleteExternalService(srvid, userid);
			SystemDictionary.webguiLog("INFO", "Delete result: " + result.getDescription());
			Executions.getCurrent().sendRedirect("");
		}
		catch (Exception e)
		{
			SystemDictionary.logException(e);
		}
	}

}


text:
What if you could create your views in UIViewController in this way:
```xml
override func viewDidLoad() {
    super.viewDidLoad()

    <UIView width=100% height=200 backgroundColor=0x74c2e1>
        <UIButton width=100% top=50 title="Push me" touchUpInside=self.buttonPushed/>
    </UIView>
    <UIView top=200 right=0 bottom=0 left=0>
        <UITableView id=tableView width=100% height=100%
            backgroundColor=UIColor.lightGrayColor() dataSource=self/>
    </UIView>

    tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "defaultCell")
}
```

With SwiftMarkup you can work in a similar way (well, not 100% similar):
```swift
override func viewDidLoad() {
    super.viewDidLoad()

    view >> {
        $<UIView>(percentWidth: 100, height: 200, backgroundColorRGB: 0x74c2e1) >> {
            $<UIButton>(title: "Push me", percentWidth: 100, top: 50,
                touchUpInside: (target: self, action: "buttonPushed"))/>
        }
        $<UIView>(top: 200, right: 0, bottom: 0, left: 0) >> {
            $<UITableView>(id: &self.tableView, dataSource: self,
                percentWidth: 100, percentHeight: 100, backgroundColor: UIColor.lightGrayColor())/>
        }
    }

    tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "defaultCell")
}
```

## Author

bugzhunter, bugzhunter@gmail.com

## License

SwiftMarkup is available under the MIT license. See the LICENSE file for more info.


text:
namespace Steinberg {
namespace Vst {

//-----------------------------------------------------------------------------
class CompressorController : public EditController, public VST3EditorDelegate
{
public:
	//------------------------------------------------------------------------
	// create function required for Plug-in factory,
	// it will be called to create new instances of this controller
	//------------------------------------------------------------------------
	static FUnknown* createInstance (void*)
	{
		return (IEditController*)new CompressorController();
	}

	//---from IPluginBase--------
	tresult PLUGIN_API initialize (FUnknown* context) SMTG_OVERRIDE;

	//---from EditController-----
	IPlugView* PLUGIN_API createView (FIDString name) SMTG_OVERRIDE;
	tresult PLUGIN_API setComponentState (IBStream* state) SMTG_OVERRIDE;
	tresult PLUGIN_API setState(IBStream* state) SMTG_OVERRIDE;
	tresult PLUGIN_API getState(IBStream* state) SMTG_OVERRIDE;
	tresult PLUGIN_API setParamNormalized(ParamID tag, ParamValue value) override;
	tresult PLUGIN_API getParamStringByValue(ParamID tag, ParamValue valueNormalized, String128 string) override;
	tresult PLUGIN_API getParamValueByString(ParamID tag, TChar* string, ParamValue& valueNormalized) override;

	//-----from VST3EditorDelegate-----//
	CView* verifyView(CView* view, const UIAttributes& attributes, const IUIDescription* description, VST3Editor* editor) override;
	IController* createSubController(UTF8StringPtr name, const IUIDescription* description, VST3Editor* editor) override;

private:
	void configDefulatShow(CControl* control);
	void configRatioShow(CControl* control);

};

//------------------------------------------------------------------------
} // namespace Vst
} // namespace Steinberg


text:
GENERATED_HEADER=gen_ogremesh.h
GENERATED_NAME=gen_ogremesh
GSOAP_PATH=/usr/include/gsoap
SOAPCPP2_FLAGS=-C -w -p ${GENERATED_NAME} -I ${GSOAP_PATH}
SOURCE_XSD=../xsd/ogremeshxml.xsd
XSD_NAMESPACE=urn:apmech/meshes
XSD_NS_PREFIX=genmesh

TYPEMAP=typemap.dat

generate: clean generate_typemap generate_header generate_classes

clean:
	- rm ${TYPEMAP}
	- rm ${GENERATED_HEADER}
	- rm ${GENERATED_NAME}*
	- rm ${XSD_NS_PREFIX}.nsmap

generate_typemap:
	echo '${XSD_NS_PREFIX} = "${XSD_NAMESPACE}"' > ${TYPEMAP}

generate_header:
	wsdl2h ${SOURCE_XSD} -o ${GENERATED_HEADER}

generate_classes:
	soapcpp2 ${SOAPCPP2_FLAGS} ${GENERATED_HEADER}
	rm ${GENERATED_NAME}Client*


text:
import { Component } from '@angular/core';

@Component({
  selector: 'jblog-licenses',
  templateUrl: './licenses.component.html',
  styleUrls: ['./licenses.component.scss']
})
export class LicensesComponent {}


text:
/*
 * ModeShape (http://www.modeshape.org)
 *
 * 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.
 */
package org.modeshape.jcr.value.binary.infinispan;

import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.junit.AfterClass;
import org.junit.BeforeClass;

public class InfinispanLocalBinaryStoreWithSingleCacheTest extends AbstractInfinispanStoreTest {

    private static final String CACHE_NAME = "singleCache";

    @AfterClass
    public static void afterClass() {
        cacheManager.getCache(CACHE_NAME).stop();
        cacheManager.removeCache(CACHE_NAME);
        InfinispanTestUtil.afterClassShutdown(cacheManager);
        binaryStore.shutdown();
    }

    protected static void startBinaryStore( Configuration metadataConfiguration,
                                            Configuration blobConfiguration ) {
        cacheManager.defineConfiguration(CACHE_NAME, metadataConfiguration);
        cacheManager.startCache(CACHE_NAME);

        binaryStore = new InfinispanBinaryStore(cacheManager, true, CACHE_NAME, CACHE_NAME);
        binaryStore.setMimeTypeDetector(DEFAULT_DETECTOR);
        binaryStore.start();
    }

    @BeforeClass
    public static void beforeClass() throws Exception {
        cacheManager = InfinispanTestUtil.beforeClassStartup(false);

        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        configurationBuilder.clustering().cacheMode(CacheMode.LOCAL);
        Configuration blobConfiguration = configurationBuilder.build();

        Configuration metadataConfiguration = configurationBuilder.build();

        startBinaryStore(metadataConfiguration, blobConfiguration);
    }
}


text:
"""Ops related to candidate sampling."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import embedding_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import nn_impl
from tensorflow.python.ops import nn_ops

def _rank_resample(weights, biases, inputs, sampled_values, num_resampled,
                   resampling_temperature, partition_strategy):
  """A helper function for rank_sampled_softmax_loss.

  This computes, for each i in `sampled_values`,

      log(sum_j exp((w_i * x_j + b_i) / resampling_temperature))

  where w_i, b_i are the weight and bias of the i-th class, respectively,
  and j ranges over the rows of `inputs`. For efficiency, we rearrange the
  computation to

      log(sum_j exp(w_i * (x_j / resampling_temperature))) +
          b_i / resampling_temperature.

  This translates to the following batched computation using tensorflow ops:

      reduce_logsumexp(matmul(embeddings,
                       transpose(inputs / resampling_temperature))) +
          biases / resampling_temperature

  The computation of the first term is colocated with the embeddings using
  `transform_fn` in `embedding_ops._embedding_lookup_and_transform`. The second
  term, not the bottleneck, is computed at the worker.

  Args:
    weights: From `rank_sampled_softmax_loss`.
    biases: From `rank_sampled_softmax_loss`.
    inputs: From `rank_sampled_softmax_loss`.
    sampled_values: A tuple of (`sampled_candidates`, `true_expected_count`,
        `sampled_expected_count`) returned by a `*_candidate_sampler` function.
    num_resampled: An `int`. This many values are selected from
        `sampled_values` using the adaptive resampling algorithm. The caller
        must ensure that `num_resampled` is less than the size of
        `sampled_values`.
    resampling_temperature: A scalar `Tensor` with the temperature parameter
        for the adaptive resampling algorithm.
    partition_strategy: From `rank_sampled_softmax_loss`.

  Returns:
    A tuple of (`resampled_candidates`, `true_expected_count`,
        `resampled_expected_count`), similar to `sampled_values` but sampled
        down to `num_resampled` values.
  """
  # This code supports passing a Tensor for num_resampled, but since it is only
  # called with an int, that's what we specify in the arg list. If this
  # function is ever externalized, we should change the doc to support Tensor.

  sampled, true_expected_count, sampled_expected_count = sampled_values

  sampled = math_ops.cast(array_ops.stop_gradient(sampled), dtypes.int64)
  true_expected_count = array_ops.stop_gradient(true_expected_count)
  sampled_expected_count = array_ops.stop_gradient(sampled_expected_count)

  reweighted_inputs = inputs / resampling_temperature

  def logsumexp_logit(embeddings):
    return math_ops.reduce_logsumexp(
        math_ops.matmul(embeddings, reweighted_inputs, transpose_b=True),
        axis=1,
        keepdims=False)

  # Calling this protected form of embedding_lookup allows co-locating
  # the logsumexp computation with the partitioned weights, which yields
  # a large speedup in practice.
  sampled_logits = embedding_ops._embedding_lookup_and_transform(  # pylint: disable=protected-access
      weights, sampled, partition_strategy, transform_fn=logsumexp_logit)
  sampled_b = array_ops.reshape(
      embedding_ops.embedding_lookup(biases, sampled, partition_strategy), [-1])
  sampled_logits += sampled_b / resampling_temperature

  _, resampled_indices = nn.top_k(sampled_logits, k=num_resampled, sorted=False)
  resampled = array_ops.gather(sampled, indices=resampled_indices)
  resampled_expected_count = array_ops.gather(
      sampled_expected_count, indices=resampled_indices)

  return resampled, true_expected_count, resampled_expected_count

def rank_sampled_softmax_loss(weights,
                              biases,
                              labels,
                              inputs,
                              num_sampled,
                              num_resampled,
                              num_classes,
                              num_true,
                              sampled_values,
                              resampling_temperature,
                              remove_accidental_hits,
                              partition_strategy,
                              name=None):
  """Computes softmax loss using rank-based adaptive resampling.

  This has been shown to improve rank loss after training compared to
  `tf.nn.sampled_softmax_loss`. For a description of the algorithm and some
  experimental results, please see: [TAPAS: Two-pass Approximate Adaptive
  Sampling for Softmax](https://arxiv.org/abs/1707.03073).

  Sampling follows two phases:
  * In the first phase, `num_sampled` classes are selected using
    `tf.nn.learned_unigram_candidate_sampler` or supplied `sampled_values`.
    The logits are calculated on those sampled classes. This phases is
    similar to `tf.nn.sampled_softmax_loss`.
  * In the second phase, the `num_resampled` classes with highest predicted
    probability are kept. Probabilities are
    `LogSumExp(logits / resampling_temperature)`, where the sum is over
    `inputs`.

  The `resampling_temperature` parameter controls the "adaptiveness" of the
  resampling. At lower temperatures, resampling is more adaptive because it
  picks more candidates close to the predicted classes. A common strategy is
  to decrease the temperature as training proceeds.

  See `tf.nn.sampled_softmax_loss` for more documentation on sampling and
  for typical default values for some of the parameters.

  This operation is for training only. It is generally an underestimate of
  the full softmax loss.

  A common use case is to use this method for training, and calculate the full
  softmax loss for evaluation or inference. In this case, you must set
  `partition_strategy="div"` for the two losses to be consistent, as in the
  following example:

  ```python
  if mode == "train":
    loss = rank_sampled_softmax_loss(
        weights=weights,
        biases=biases,
        labels=labels,
        inputs=inputs,
        ...,
        partition_strategy="div")
  elif mode == "eval":
    logits = tf.matmul(inputs, tf.transpose(weights))
    logits = tf.nn.bias_add(logits, biases)
    labels_one_hot = tf.one_hot(labels, n_classes)
    loss = tf.nn.softmax_cross_entropy_with_logits(
        labels=labels_one_hot,
        logits=logits)
  ```

  Args:
    weights: A `Tensor` or `PartitionedVariable` of shape `[num_classes, dim]`,
        or a list of `Tensor` objects whose concatenation along dimension 0
        has shape [num_classes, dim]. The (possibly-sharded) class embeddings.
    biases: A `Tensor` or `PartitionedVariable` of shape `[num_classes]`.
        The (possibly-sharded) class biases.
    labels: A `Tensor` of type `int64` and shape `[batch_size,
        num_true]`. The target classes. Note that this format differs from
        the `labels` argument of `nn.softmax_cross_entropy_with_logits`.
    inputs: A `Tensor` of shape `[batch_size, dim]`. The forward
        activations of the input network.
    num_sampled: An `int`. The number of classes to randomly sample per batch.
    num_resampled: An `int`. The number of classes to select from the
        `num_sampled` classes using the adaptive resampling algorithm. Must be
        less than `num_sampled`.
    num_classes: An `int`. The number of possible classes.
    num_true: An `int`.  The number of target classes per training example.
    sampled_values: A tuple of (`sampled_candidates`, `true_expected_count`,
        `sampled_expected_count`) returned by a `*_candidate_sampler` function.
        If None, default to `nn.learned_unigram_candidate_sampler`.
    resampling_temperature: A scalar `Tensor` with the temperature parameter
        for the adaptive resampling algorithm.
    remove_accidental_hits: A `bool`. Whether to remove "accidental hits"
        where a sampled class equals one of the target classes.
    partition_strategy: A string specifying the partitioning strategy, relevant
        if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
        See `tf.nn.embedding_lookup` for more details.
    name: A name for the operation (optional).

  Returns:
    A `batch_size` 1-D tensor of per-example sampled softmax losses.

  Raises:
    ValueError: If `num_sampled <= num_resampled`.
  """
  if num_sampled > num_classes:
    raise ValueError("num_sampled ({}) cannot be greater than num_classes ({})".
                     format(num_sampled, num_classes))
  if num_sampled <= num_resampled:
    raise ValueError("num_resampled ({}) must be less than num_sampled ({})".
                     format(num_resampled, num_sampled))
  if partition_strategy not in ("div", "mod"):
    raise ValueError(
        "unsupported partition_strategy ({})".format(partition_strategy))
  with ops.name_scope(name, "rank_sampled_softmax_loss", [
      weights, biases, labels, inputs, sampled_values, resampling_temperature
  ]) as name:
    if not sampled_values:
      sampled_values = nn.learned_unigram_candidate_sampler(
          true_classes=labels,
          num_true=num_true,
          num_sampled=num_sampled,
          unique=True,
          range_max=num_classes)
    # From sampled_values, select the top num_resampled values using the
    # adaptive rank resampling strategy.
    resampled_values = _rank_resample(weights, biases, inputs, sampled_values,
                                      num_resampled, resampling_temperature,
                                      partition_strategy)
    return nn.sampled_softmax_loss(
        weights=weights,
        biases=biases,
        labels=labels,
        inputs=inputs,
        num_sampled=num_resampled,
        num_classes=num_classes,
        num_true=num_true,
        sampled_values=resampled_values,
        remove_accidental_hits=remove_accidental_hits,
        partition_strategy=partition_strategy,
        name=name)

def sampled_sparse_softmax_loss(weights,
                                biases,
                                labels,
                                inputs,
                                num_sampled,
                                num_classes,
                                sampled_values=None,
                                remove_accidental_hits=True,
                                partition_strategy="mod",
                                name="sampled_sparse_softmax_loss"):
  """Computes and returns the sampled sparse softmax training loss.

  This is a faster way to train a softmax classifier over a huge number of
  classes.

  This operation is for training only.  It is generally an underestimate of
  the full softmax loss.

  A common use case is to use this method for training, and calculate the full
  softmax loss for evaluation or inference. In this case, you must set
  `partition_strategy="div"` for the two losses to be consistent, as in the
  following example:

  ```python
  if mode == "train":
    loss = tf.nn.sampled_sparse_softmax_loss(
        weights=weights,
        biases=biases,
        labels=labels,
        inputs=inputs,
        ...,
        partition_strategy="div")
  elif mode == "eval":
    logits = tf.matmul(inputs, tf.transpose(weights))
    logits = tf.nn.bias_add(logits, biases)
    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
        labels=tf.squeeze(labels),
        logits=logits)
  ```

  See our [Candidate Sampling Algorithms Reference]
  (https://www.tensorflow.org/extras/candidate_sampling.pdf)

  Also see Section 3 of [Jean et al., 2014](http://arxiv.org/abs/1412.2007)
  ([pdf](http://arxiv.org/pdf/1412.2007.pdf)) for the math.

  Args:
    weights: A `Tensor` of shape `[num_classes, dim]`, or a list of `Tensor`
        objects whose concatenation along dimension 0 has shape
        [num_classes, dim].  The (possibly-sharded) class embeddings.
    biases: A `Tensor` of shape `[num_classes]`.  The class biases.
    labels: A `Tensor` of type `int64` and shape `[batch_size, 1]`.
        The index of the single target class for each row of logits.  Note that
        this format differs from the `labels` argument of
        `nn.sparse_softmax_cross_entropy_with_logits`.
    inputs: A `Tensor` of shape `[batch_size, dim]`.  The forward
        activations of the input network.
    num_sampled: An `int`.  The number of classes to randomly sample per batch.
    num_classes: An `int`. The number of possible classes.
    sampled_values: a tuple of (`sampled_candidates`, `true_expected_count`,
        `sampled_expected_count`) returned by a `*_candidate_sampler` function.
        (if None, we default to `log_uniform_candidate_sampler`)
    remove_accidental_hits:  A `bool`.  whether to remove "accidental hits"
        where a sampled class equals one of the target classes.  Default is
        True.
    partition_strategy: A string specifying the partitioning strategy, relevant
        if `len(weights) > 1`. Currently `"div"` and `"mod"` are supported.
        Default is `"mod"`. See `tf.nn.embedding_lookup` for more details.
    name: A name for the operation (optional).

  Returns:
    A `batch_size` 1-D tensor of per-example sampled softmax losses.

  """
  logits, _ = nn_impl._compute_sampled_logits(
      weights=weights,
      biases=biases,
      labels=labels,
      inputs=inputs,
      num_sampled=num_sampled,
      num_classes=num_classes,
      num_true=1,
      sampled_values=sampled_values,
      subtract_log_q=True,
      remove_accidental_hits=remove_accidental_hits,
      partition_strategy=partition_strategy,
      name=name)

  # There is only one true label. _compute_sampled_logits puts the true logit
  # at index 0.
  labels = array_ops.zeros([array_ops.shape(logits)[0], 1], dtype=dtypes.int64)

  sampled_losses = nn_ops.sparse_softmax_cross_entropy_with_logits(
      labels=array_ops.squeeze(labels), logits=logits)
  # sampled_losses is a [batch_size] tensor.
  return sampled_losses


text:
/**
 * view/rooms/list/ListController.js
 *
 * Manages List View page state.
 */
import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import camelCase from 'camelcase';
import Parser from 'html-react-parser';

class ListController extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const {
      tableHeaders,
      tableRows,
    } = this.props;

    return (

              {tableHeaders.map(header => {
                const key = camelCase(header);
                return

{header}

                	;
              })}

            {tableRows.map(row => {
              const camelCaseHeaders = tableHeaders.map(header => camelCase(header));
              return

                {camelCaseHeaders.map(header =>

                    {Parser(row[header])}
                  	)}

;
            })}

    );
  }
}

ListController.propTypes = {
  tableHeaders: PropTypes.array,
  tableRows: PropTypes.array,
};

ListController.defaultProps = {
  tableHeaders: [],
  tableRows: [],
};

export default ListController;


text:
package com.home.rxtwitch.ui.widget;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.IdRes;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;

import com.home.rxtwitch.R;
import com.home.rxtwitch.util.ActivityCastUtil;
import com.home.rxtwitch.util.DensityUtil;

/**
 * Created by xmax on 6/23/16.
 */

public class PopupMenu extends PopupWindow implements View.OnClickListener {
    private Activity mActivity;
    private OnItemClickListener mOnItemClickListener;
    private ImageView mItem1ChooseIV;
    private ImageView mItem2ChooseIV;
    private View mPopMenu;

    public enum MenuItem {
        ITEM1, ITEM2, ITEM3, ITEM4
    }

    public PopupMenu(Context context) {
        super(context);
        this.mActivity = ActivityCastUtil.scanForActivity(context);
        LayoutInflater inflater = LayoutInflater.from(context);
        mPopMenu = inflater.inflate(R.layout.popup_menu_main, null);
        this.setContentView(mPopMenu);
        this.setWidth(DensityUtil.dp2px(context, 200));
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        this.setTouchable(true);
        this.setOutsideTouchable(true);
        this.setElevation(50);
        this.setBackgroundDrawable(mActivity.getDrawable(R.drawable.pop_menu_bg));

        View item1 = mPopMenu.findViewById(R.id.menu_item1);
        View item2 = mPopMenu.findViewById(R.id.menu_item2);
        View item3 = mPopMenu.findViewById(R.id.menu_item3);
        View item4 = mPopMenu.findViewById(R.id.menu_item4);

        mItem1ChooseIV = (ImageView) mPopMenu.findViewById(R.id.menu_item1_choose);
        mItem2ChooseIV = (ImageView) mPopMenu.findViewById(R.id.menu_item2_choose);

        //set padding top 8dp, make sure each items have same visible height in pop window.
        /*View item0 = mPopMenu.findViewById(R.id.item0);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) item0.getLayoutParams();
        params.height = dip2px(activity, 8);
        item0.setLayoutParams(params);*/

        item1.setOnClickListener(this);
        item2.setOnClickListener(this);
        item3.setOnClickListener(this);
        item4.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        MenuItem menuItem = null;
        switch (v.getId()) {
            case R.id.menu_item1:
                menuItem = MenuItem.ITEM1;
                break;
            case R.id.menu_item2:
                menuItem = MenuItem.ITEM2;
                break;
            case R.id.menu_item3:
                menuItem = MenuItem.ITEM3;
                break;
            case R.id.menu_item4:
                menuItem = MenuItem.ITEM4;
                break;
        }
        checkItem(menuItem);
        if (mOnItemClickListener != null)
            mOnItemClickListener.onClick(menuItem);
        dismiss();
    }

    public void checkItem(MenuItem item) {
        if (item.equals(MenuItem.ITEM1)) {
            mItem1ChooseIV.setVisibility(View.VISIBLE);
            mItem2ChooseIV.setVisibility(View.INVISIBLE);
        } else if (item.equals(MenuItem.ITEM2)) {
            mItem1ChooseIV.setVisibility(View.INVISIBLE);
            mItem2ChooseIV.setVisibility(View.VISIBLE);
        }
    }

    public View findViewById(@IdRes int id) {
        return mPopMenu.findViewById(id);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }

    public void showLocation(@IdRes int resId) {
        showAsDropDown(mActivity.findViewById(resId), DensityUtil.dp2px(mActivity, -8),
                DensityUtil.dp2px(mActivity, -8), Gravity.TOP | Gravity.END);
    }

    private int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    public interface OnItemClickListener {
        void onClick(MenuItem item);
    }

}


text:
@interface AppDelegate : UIResponder <UIApplicationDelegate, WXApiDelegate>
{
    NSString *wbtoken;
    NSString *webCurrentUserID;

}
@property (nonatomic, strong) NSString *wbtoken;
@property (nonatomic, strong) NSString *webCurrentUserID;
@property (nonatomic, strong) NSString *wbRefreshToken;
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, strong) UITabBarController *tabBarVC;

@end


text:
This module helps generating PDF documents dynamically from your Play! web application.
It simply renders your HTML- and CSS-based templates to PDF.
It is based on the Flying Saucer library, which in turn uses iText for PDF generation.

## Usage

I created an example application https://github.com/benjohnde/play-pdf/tree/master/example.

You can use a standard Play! scala template like this one:
```html
@(message: String)

@main("Welcome to Play 2.6.2") {
    Image: <img src="/public/images/favicon.png"/><br/>
    Hello world! <br/>
    @message <br/>
}
```

Then this template, after having imported `de.benjohn.play.pdf.PDF`, can simply be rendered as:

```java
public static Result document() {
    return PDF.ok(document.render("Your new application is ready."));
}
```
where ```PDF.ok``` is a simple shorthand notation for:
```java
public static Result document() {
    return ok(PDF.toBytes(document.render("Your new application is ready."))).as("application/pdf")
}
```

## Template rules

Templates must generate XHTML.

If the template is using an image, stylesheet, etc., it usually is loaded via an http call.
The PDF modules tries to optimize that resource loading:
If you specify the URI as a path into the classpath of your Play! app, the resource is loaded directly instead.
See the above sample template for an example.

Of course you can link to CSS files in your class path also, but be aware not to
use the `media="screen"` qualifier.

Fonts you use must be explicitely packaged with your app.

```html
<html>
    <head>
        <style>
            body { font-family: FreeSans; }
        </style>
    </head>
    <body>
    ...
    </body>
</html>
```

The module imports font resources as specified in your [application configuration](https://github.com/benjohnde/play-pdf/blob/master/example/conf/application.conf).

Specify fonts as follows:

```bash
pdf.fonts = ["Arial.ttf", "Helvetica.ttf"]
```

Each font file should be placed in your Play app configuration folder, so that they will be included.
See also the example project.

## Installation

Currently the module is not hosted anywhere. In order to use it, you need to publish it locally in the current play-maven-repository. Therefore:

```bash
git clone https://github.com/benjohnde/play-pdf.git
cd play-pdf/module
sbt publish-local
```

Then, add to your libraryDependencies in your `build.sbt`:

```scala
libraryDependencies ++= Seq(
    "de.benjohn.play" %% "pdf" % "1.1.3"
)
```

After the next restart of the `sbt`, the module should be available.
If you are using an IDE like Eclipse, remember to re-generate your project files.

## Kudos

- [joergviola](https://github.com/joergviola) initial creator of this project


text:
module Util.Monad
  ( -- * Boolean helpers
    andM
  , orM
  , allM
  , anyM
    -- * List helpers
  , concatMapM
  , mapMaybeM
  , partitionM
  , breakM
  , nubByM
    -- * ListT helpers
  , pickOne
  , pickFromList
  , guardM
    -- * ExceptT helpers
  , tryError
  , mapMCollectErrors
  , mapMCollectErrors_
  , forMCollectErrors
  , forMCollectErrors_
  ) where

import           Control.Applicative
import           Control.Monad
import           Control.Monad.Except
import           Control.Monad.List
import           Data.Either          (partitionEithers)
import           Data.Foldable
import           Data.Maybe           (catMaybes)

andM :: Monad m => m Bool -> m Bool -> m Bool
andM mp mq = do
  p <- mp
  if p then mq else return False

orM :: Monad m => m Bool -> m Bool -> m Bool
orM mp mq = do
  p <- mp
  if p then return True else mq

allM :: Monad m => (a -> m Bool) -> [a] -> m Bool
allM _ [] = return True
allM test (x:xs) = do
  result <- test x
  if result then allM test xs else return False

anyM :: Monad m => (a -> m Bool) -> [a] -> m Bool
anyM _ [] = return False
anyM test (x:xs) = do
  result <- test x
  if result then return True else anyM test xs

pickOne :: Monad m => m [a] -> ListT m a
pickOne = ListT

pickFromList :: Monad m => [a] -> ListT m a
pickFromList = ListT . return

guardM :: (Monad m, MonadTrans t, Monad (t m), Alternative (t m)) => m Bool -> t m ()
guardM test = lift test >>= guard

concatMapM :: (Monad m, Traversable t) => (a -> m [b]) -> t a -> m [b]
concatMapM f = fmap concat . mapM f

mapMaybeM :: Monad m => (a -> m (Maybe b)) -> [a] -> m [b]
mapMaybeM f = fmap catMaybes . mapM f

partitionM :: (Foldable t, Monad m) => (a -> m Bool) -> t a -> m ([a], [a])
partitionM p = foldrM (select p) ([],[])
{-# INLINE partitionM #-}

select :: Monad m => (a -> m Bool) -> a -> ([a], [a]) -> m ([a], [a])
select p x (ts, fs) = do
  px <- p x
  return $ if px then (x:ts, fs) else (ts, x:fs)

breakM :: (Monad m) => (a -> m Bool) -> [a] -> m ([a], [a])
breakM _ [] = return ([], [])
breakM p xs@(x:xs') = do
  px <- p x
  if px
    then return ([], xs)
    else do
      (ys, zs) <- breakM p xs'
      return (x:ys, zs)

nubByM :: Monad m => (a -> a -> m Bool) -> [a] -> m [a]
nubByM eq l = nubBy' l []
  where
    nubBy' [] _ = return []
    nubBy' (y:ys) alreadyAdded = do
      hasDuplicate <- anyM (eq y) alreadyAdded
      if hasDuplicate
        then nubBy' ys alreadyAdded
        else (y:) <$> nubBy' ys (y : alreadyAdded)

-- | Given an action that may fail throwing and error, execute it for every item
-- of the list regardless if any action fails, accumulating the results or
-- errors. If any action fails, accumulates all errors and throw them together.
--
-- Be /very careful/ when using this: any side effects that happen for any
-- sucessful item will /not/ be rolled back.
--
-- Unlike 'mapM', this doesn't stop when the first error is thrown. Instead, the
-- action is still executed with the remaining items of the list, accumulating
-- errors instead of results. Then, at the very end, the accumulated errors are
-- thrown.
mapMCollectErrors :: (Monoid e, MonadError e m) => (a -> m b) -> [a] -> m [b]
mapMCollectErrors fn xs = do
  results <- mapM (tryError . fn) xs
  let (errors, values) = partitionEithers results
  if null errors
    then return values
    else throwError (mconcat errors)

-- | Like 'mapMCollectErrors', but doesn't return the result list.
mapMCollectErrors_ :: (Monoid e, MonadError e m) => (a -> m b) -> [a] -> m ()
mapMCollectErrors_ fn xs = mapMCollectErrors fn xs >> return ()

-- | Like 'mapMCollectErrors', but with the arguments fliped.
forMCollectErrors :: (Monoid e, MonadError e m) => [a] -> (a -> m b) -> m [b]
forMCollectErrors = flip mapMCollectErrors

-- | Like 'mapMCollectErrors', but has the arguments fliped and doesn't return
-- the result list.
forMCollectErrors_ :: (Monoid e, MonadError e m) => [a] -> (a -> m b) -> m ()
forMCollectErrors_ = flip mapMCollectErrors_

-- | Execute the action and catch any thrown errors.
tryError :: MonadError e m => m a -> m (Either e a)
tryError action =
  (Right <$> action) `catchError` (return . Left)


text:
package org.apache.flex.forks.batik.css.dom;

import org.apache.flex.forks.batik.css.engine.CSSEngine;
import org.apache.flex.forks.batik.css.engine.StyleDeclaration;
import org.apache.flex.forks.batik.css.engine.StyleDeclarationProvider;
import org.apache.flex.forks.batik.css.engine.value.Value;

/**
 * A class for SVG style declarations that store their properties in a
 * {@link org.apache.flex.forks.batik.css.engine.StyleDeclaration}.
 *
 * @author Cameron McCormack
 * @version $Id: CSSOMStoredStyleDeclaration.java 475477 2006-11-15 22:44:28Z cam $
 */
public abstract class CSSOMStoredStyleDeclaration
    extends CSSOMSVGStyleDeclaration
    implements CSSOMStyleDeclaration.ValueProvider,
               CSSOMStyleDeclaration.ModificationHandler,
               StyleDeclarationProvider {

    /**
     * The object storing the properties.
     */
    protected StyleDeclaration declaration;

    /**
     * Creates a new CSSOMStoredStyleDeclaration.
     */
    public CSSOMStoredStyleDeclaration(CSSEngine eng) {
        super(null, null, eng);
        valueProvider = this;
        setModificationHandler(this);
    }

    /**
     * Returns the object storing the properties of this style declaration.
     */
    public StyleDeclaration getStyleDeclaration() {
        return declaration;
    }

    /**
     * Sets the object storing the properties of this style declaration.
     */
    public void setStyleDeclaration(StyleDeclaration sd) {
        declaration = sd;
    }

    // ValueProvider /////////////////////////////////////////////////////////

    /**
     * Returns the current value associated with this object.
     */
    public Value getValue(String name) {
        int idx = cssEngine.getPropertyIndex(name);
        for (int i = 0; i < declaration.size(); i++) {
            if (idx == declaration.getIndex(i)) {
                return declaration.getValue(i);
            }
        }
        return null;
    }

    /**
     * Tells whether the given property is important.
     */
    public boolean isImportant(String name) {
        int idx = cssEngine.getPropertyIndex(name);
        for (int i = 0; i < declaration.size(); i++) {
            if (idx == declaration.getIndex(i)) {
                return declaration.getPriority(i);
            }
        }
        return false;
    }

    /**
     * Returns the text of the declaration.
     */
    public String getText() {
        return declaration.toString(cssEngine);
    }

    /**
     * Returns the length of the declaration.
     */
    public int getLength() {
        return declaration.size();
    }

    /**
     * Returns the value at the given.
     */
    public String item(int idx) {
        return cssEngine.getPropertyName(declaration.getIndex(idx));
    }
}