text:
var sys = require('util');
var util = require('./../util.js');
var db;

exports.setPeers = function (p) {
  // i use this to set the reference
  // to the completed peers object. otherwise
  // the complete object will not be available
  // at the time its called. surely there's a
  // less retarded way of accomplishing this
  db = p;
}

function dbCallback(cb, err, n, successHook) {
	if(err||typeof n=='undefined') {
	  cb(err);
	} else {
	  if(n==null) { // fucked
	    cb(new Error("Database returned null doc with no error!"));
	  }
	  if(typeof successHook=='function') {
	    successHook(n);
	  }
	  cb(null,n);
	}
}

exports.NetworkPeer = {

  storeNew: function (o, cb) {
    var net = new model.factories.Network({
        name:o.name,
        rid:parseInt(o.rid),
        is_private:false,
        company:o.company
    });
  	db.Network.create(net, function(err, n) {
      dbCallback(cb, err, n);
  	});
  },
  updateDoc: function (o, cb) {
    var q = {
      rid: parseInt(o.rid)
    }
    db.Network.update(q, o, function (err, n) {
      dbCallback(cb, err, n);
  	});
  },
  updateReadCount: function (id, cb) {
    db.Network.update({ rid: id }, {$inc:{reads:1}}, cb);
  },
  updateWriteCount: function (id, cb) {
    db.Network.update({ rid: id }, {$inc:{writes:1}}, cb);
  },
  refreshKeysById: function (id, cb) {

    var k = util.randomString(40);
    var s = util.randomString(40);

    db.Network.collection.update(
      { rid: id }, {$set:{admin_key:k, admin_secret:s}},
      cb
    );

  },
  countGroupPosts: function (id, cb) {
    db.Network.findById(id, function (e, n) {
      if(e) cb(e,null);
      var coll = {};
      db.Note.find({ // find all notes for network
        rid:n.rid
      }).select('gid').each(function (e,d) { // select only gid field
        if(e) cb(e);
        //TODO use map-reduce for this??
        if(d==null) {
          cb(null,coll);
        } else {
          if(!coll[d.gid]) {
            coll[d.gid] = 0;
          }
          coll[d.gid]++;
        }
      });
    });
  },
  getOne: function (id, cb) {
    //TODO check for valid object id before proceeding

  	db.Network.findById(id, function (err, n) {
      dbCallback(cb, err, n);
  	});
  },
  removeOne: function (id, cb) {
  	db.Network.findById( id , function (err, n) {
  	  console.log('model:found note, calling back...');
  	  dbCallback(cb, err, n, function (n) {
  	    console.log('model:db callback complete');
  	    n.remove();
  	  });
  	});
  },
  getByRemoteId: function (id, cb) {
    var q = (id) ? { rid: parseInt(id) } : {};
  	db.Network.find(q, cb);
  }
};

exports.NotePeer = {

  get: function (crit, cb) {
    console.log(crit);
    if(typeof crit == 'undefined') throw ("Criteria cannot be undefined!");
  	db.Note.find(crit).sort('-_id').sort('-crstamp').limit(20).exec(cb);
  },
  updateFlagCount: function (id, cb) {
    db.Note.update({ _id: id }, {$inc:{flags:1}}, cb);
  },
  getActivity: function (crit, cb) { // meant for admin use only
    if(typeof crit == 'undefined') throw ("Criteria cannot be undefined!");

  	db.Note.find(crit).sort('-_id').limit(20).sort('-crstamp').exec(cb);
  },
  removeOne: function (id, cb) {
  	db.Note.findById( id , function (err, n) {
  	  dbCallback(cb, err, n, function (n) {
  	    n.remove();
  	  });
  	});
  },
  getOne: function (id, cb) {
    db.Note.findById(id, cb);
  },

  storeNew: function (note, cb) {
  	var q = { name: db.Note.gid };
    db.Group.update( q, { $inc: { notes: 1 } }, { upsert:true }, function(err){
      if(err) {
        (err, null);
      } else {
        note.crstamp = (new Date()).getTime();
      	var post = new db.Note(note);
      	post.save(cb);
      }
    }); // upsert=true: insert if not there

  }
};

exports.ResponsePeer = {

  get: function (crit, cb) {

    if(typeof crit == 'undefined') throw ("Criteria cannot be undefined!");
  	db.Response.find(crit).sort('-crstamp').limit(20).exec(cb);
  },
  storeNew: function (resp, cb) {

  	resp.crstamp = (new Date()).getTime();
  	var response = new db.Response(resp);
  	response.save(cb);

  }
};

exports.FlyleafPeer = {

  getOne: function (id, cb) {
    db.Flyleaf.findById(id, cb);
  }

};

exports.ThumbprintPeer = {

  findOneByParHash: function (par_hash, cb) {

  	db.Thumbprint.findOne({
  	  par_hash: par_hash
  	}, function (err,doc) {
  	  console.log('back from db');
  	  console.log(err);
  	  console.log(doc);
  	  if(!doc && !err) {
  	    console.log('not found');
  	  }
  	  cb(err,doc);
  	});
  },
  /* Temporary convenience -- when called from note create, this allows anyone to modify a publisher's content */
  storeNew: function (crit, cb) {
  	db.Thumbprint.update({ par_hash: crit.par_hash }, crit, {upsert:true}, function (err, d) {
  	  if(err) return cb(err);
  	  cb(null,d);
  	});
  }
};

exports.ImagePeer = {
  getOne: function (name, cb) {
  	db.Image.findOne({name:name}, cb);
  },
  storeNew: function (o, cb) {
  	var img = new db.Image(o);
  	img.save(cb);
  }
};

exports.GroupPeer = {

  getOne: function (id, cb) {

    var q = { name:id };
    var g = { $inc: { queries: 1 } };

    db.Group.findOne(q, function (err, doc) {
      if(!doc) {
        db.Group.create({
         name:id.toLowerCase(),
         queries:0,
         notes:0
        }, cb);
      } else {
        db.Group.update(q, g, function (e,d) {
          cb(err,doc);
        });
      }
    });

  },
  getIdList: function (crit, cb) {

    db.Note.find(crit).select('gid').distinct('gid', function (e,d) {
      if(e) cb(e);
      cb(null,d);
    });

  }

};

exports.UserPeer = {

  getOne: function (id, cb) {
    var q = { name:id };
    var g = { $inc: { queries: 1 } };
    db.User.update(q, g, true, false);
    db.User.findOne(q, cb);
  },

  storeNew: function (user, cb) {

  	var q = {uid:db.User.uid,udom:db.User.udom};
  	db.User.update(q, user, {upsert:true}, function () {
  	  db.User.update(q, {$inc:{logins:1}},{upsert:true},cb);
  	});

  },

  findByDomainAndId: function (udom, id, cb) {

    var q = {uid:id,udom:udom};

    console.log(q);

    db.User.findOne(q, function (err, user) {

      console.log('returned from db');

      if(err) {
        console.log(err);
        return cb(err);
      }
      console.log(user);

      return cb(null,user);

    });

  },

  createWithFB: function (fbUserMeta, accessToken, expires, callback) {
    var expiresDate = new Date;
    expiresDate.setSeconds(expiresDate.getSeconds() + expires);

    var params =  {
      fb: {
          id: fbUserMeta.id
        , accessToken: accessToken
        , expires: expiresDate
        , name: {
              full: fbUserMeta.name
            , first: fbUserMeta.first_name
            , last: fbUserMeta.last_name
          }
        , alias: fbUserMeta.link.match(/^http:\/\/www.facebook\.com\/(.+)/)[1]
        , gender: fbUserMeta.gender
        , email: fbUserMeta.email
        , timezone: fbUserMeta.timezone
        , locale: fbUserMeta.locale
        , verified: fbUserMeta.verified
        , updatedTime: fbUserMeta.updated_time
      }
    };

    // TODO Only do this if password module is enabled
    //      Currently, this is not a valid way to check for enabled
    /*
    if (everyauth.password)
      params[everyauth.password.loginKey()] = "fb:" + fbUserMeta.id; // Hack because of way mongodb treate unique indexes
    */
    this.create(params, callback);
  },

  createWithTwitter: function (twitUserMeta, accessToken, accessTokenSecret, callback) {
      var params = {
        twit: {
            accessToken: accessToken
          , accessTokenSecret: accessTokenSecret
          , id: twitUserMeta.id
          , name: twitUserMeta.name
          , screenName: twitUserMeta.screen_name
          , location: twitUserMeta.location
          , description: twitUserMeta.description
          , profileImageUrl: twitUserMeta.profile_image_url
          , url: twitUserMeta.url
          , protected: twitUserMeta.protected
          , followersCount: twitUserMeta.followers_count
          , profileBackgroundColor: twitUserMeta.profile_background_color
          , profileTextColor: twitUserMeta.profile_text_color
          , profileLinkColor: twitUserMeta.profile_link_color
          , profileSidebarFillColor: twitUserMeta.profile_sidebar_fill_color
          , profileSiderbarBorderColor: twitUserMeta.profile_sidebar_border_color
          , friendsCount: twitUserMeta.friends_count
          , createdAt: twitUserMeta.created_at
          , favouritesCount: twitUserMeta.favourites_count
          , utcOffset: twitUserMeta.utc_offset
          , timeZone: twitUserMeta.time_zone
          , profileBackgroundImageUrl: twitUserMeta.profile_background_image_url
          , profileBackgroundTile: twitUserMeta.profile_background_tile
          , profileUseBackgroundImage: twitUserMeta.profile_use_background_image
          , geoEnabled: twitUserMeta.geo_enabled
          , verified: twitUserMeta.verified
          , statusesCount: twitUserMeta.statuses_count
          , lang: twitUserMeta.lang
          , contributorsEnabled: twitUserMeta.contributors_enabled
        }
      };

      // TODO Only do this if password module is enabled
      //      Currently, this is not a valid way to check for enabled
      /*if (everyauth.password)
        params[everyauth.password.loginKey()] = "twit:" + twitUserMeta.id; // Hack because of way mongodb treate unique indexes
      */
      this.create(params, callback);
    },

    createWithGoogleOAuth: function (googleUser, accessToken, accessTokenExtra, callback) {
      var expiresDate = new Date;
      expiresDate.setSeconds(expiresDate.getSeconds() + accessTokenExtra.expires_in);

      var params = {
        google: {
            email: googleUser.id
          , expires: expiresDate
          , accessToken: accessToken
          , refreshToken: accessTokenExtra.refresh_token
        }
      };

      this.create(params, callback);
    },

    createWithTumblr: function (tumblrUser, accessToken, accessTokenSecret, callback) {
      var expiresDate = new Date;
      expiresDate.setSeconds(expiresDate.getSeconds() + accessTokenExtra.expires_in);

      console.log(tumblrUser.user);

      var params = {
        tumblr: {
            id: tumblrUser.user.name
          , accessToken: accessToken
          , accessTokenSecret: accessTokenSecret
          , verifier: tumblrUser.verifier
        }
      };

      this.create(params, callback);
    }

};


text:
package org.develnext.jphp.parser.classes;

import org.develnext.jphp.core.syntax.SyntaxAnalyzer;
import org.develnext.jphp.core.tokenizer.Tokenizer;
import org.develnext.jphp.core.tokenizer.token.expr.value.NameToken;
import org.develnext.jphp.core.tokenizer.token.stmt.*;
import org.develnext.jphp.core.tokenizer.token.stmt.NamespaceUseStmtToken.UseType;
import org.develnext.jphp.parser.ParserExtension;
import php.runtime.Memory;
import php.runtime.annotation.Reflection.*;
import php.runtime.common.Callback;
import php.runtime.env.Context;
import php.runtime.env.Environment;
import php.runtime.ext.core.classes.stream.Stream;
import php.runtime.ext.core.classes.stream.WrapIOException;
import php.runtime.lang.BaseObject;
import php.runtime.lang.exception.BaseParseError;
import php.runtime.reflection.ClassEntity;

import java.io.File;
import java.io.IOException;

@Namespace(ParserExtension.NS)
public class SourceFile extends BaseObject {
    interface FetchFullNameHandler {
        String fetch(String name, NamespaceStmtToken baseNamespace, UseType useType);
    }

    protected Memory path;
    protected String uniqueId;

    private Context context;
    private ModuleRecord moduleRecord;
    private FetchFullNameHandler fetchFullNameHandler;

    public SourceFile(Environment env) {
        super(env);
    }

    public SourceFile(Environment env, ClassEntity clazz) {
        super(env, clazz);
        moduleRecord = new ModuleRecord(env);
    }

    @Signature
    public void __construct(Environment env, Memory path, String uniqueId) {
        this.path = path;
        this.uniqueId = uniqueId;

        try {
            this.context = new Context(Stream.getInputStream(env, path));
        } catch (WrapIOException e) {
            this.context = new Context(new File(path.toString()));
        }
    }

    @Getter
    public String getUniqueId() {
        return uniqueId;
    }

    @Getter
    public Memory getPath() {
        return path;
    }

    @Getter
    public ModuleRecord getModuleRecord() {
        return moduleRecord;
    }

    @Setter
    public void setModuleRecord(ModuleRecord moduleRecord) {
        this.moduleRecord = moduleRecord;
    }

    @Signature
    public boolean isReadOnly() {
        return !getContext().isLikeFile();
    }

    @Signature
    public String fetchFullName(String name, NamespaceRecord namespace, UseType useType) {
        if (namespace.token instanceof NamespaceStmtToken) {
            return fetchFullNameHandler == null ? name : fetchFullNameHandler.fetch(name, (NamespaceStmtToken) namespace.token, useType);
        } else {
            throw new IllegalArgumentException("namespace must be NamespaceStmt token!");
        }
    }

    @Signature({
            @Arg(value = "manager", nativeType = SourceManager.class)
    })
    public Memory update(Environment env, Memory... args) {
        SourceManager manager = args[0].toObject(SourceManager.class);

        try {
            moduleRecord.clear();
            Tokenizer tokenizer = new Tokenizer(context);

            SyntaxAnalyzer analyzer = new SyntaxAnalyzer(manager.env, tokenizer);

            fetchFullNameHandler = new FetchFullNameHandler() {
                @Override
                public String fetch(String name, NamespaceStmtToken baseNamespace, UseType useType) {
                    return analyzer.getRealName(NameToken.valueOf(name), baseNamespace, useType).toName();
                }
            };

            for (ClassStmtToken token : analyzer.getClasses()) {
                moduleRecord.synchronize(env, token, tokenizer);
            }

            for (FunctionStmtToken token : analyzer.getFunctions()) {
                moduleRecord.synchronize(env, token, tokenizer);
            }

            for (ConstStmtToken token : analyzer.getConstants()) {
                moduleRecord.synchronize(env, token, tokenizer);
            }
        } catch (BaseParseError | IOException e) {
        }

        return Memory.NULL;
    }

    public Context getContext() {
        return context;
    }
}

redpajama_set_name: RedPajamaGithub


text:
sap.ui.define(["exports"], function (_exports) {
  "use strict";

  Object.defineProperty(_exports, "__esModule", {
    value: true
  });
  _exports.default = void 0;

  /**
   * Returns the normalized event target in cases when it has shadow root.
   * @param {Object} target The original event target
   * @returns {Object} The normalized target
   */
  const getNormalizedTarget = target => {
    let element = target;

    if (target.shadowRoot && target.shadowRoot.activeElement) {
      element = target.shadowRoot.activeElement;
    }

    return element;
  };

  var _default = getNormalizedTarget;
  _exports.default = _default;
});


text:
package io.github.classgraph.test.accepted;

/**
 * Cls.
 */
public class Cls {
}


text:
import { colors } from './tailwind-values'

export default {
  name: 'Lichter.io',
  lang: 'en',
  short_name: 'Lichter.io',
  start_url: '/',
  display: 'standalone',
  background_color: colors['gray-200'],
  theme_color: colors['red-500']
}


text:
package com.google.developers.api;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by renfeng on 6/22/15.
 */
public class DriveManager extends ClientManager<Drive> {

	public DriveManager(HttpTransport transport, JsonFactory jsonFactory,
						Credential credential) {

		Drive drive = new Drive.Builder(transport, jsonFactory, credential)
				.setApplicationName(GoogleOAuth2.APPLICATION_NAME)
				.build();

		setClient(drive);
	}

	/**
	 * Download a file's content.
	 *
	 * @param service Drive API service instance.
	 * @param file    Drive File instance.
	 * @return InputStream containing the file's content if successful,
	 * {@code null} otherwise.
	 */
	private static InputStream downloadFile(Drive service, File file) {

		/*
		 * https://developers.google.com/drive/web/manage-downloads
		 */

		if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
			try {
				// uses alt=media query parameter to request content
				return service.files().get(file.getId()).executeMediaAsInputStream();
			} catch (IOException e) {
				// An error occurred.
				e.printStackTrace();
				return null;
			}
		} else {
			// The file doesn't have any content stored on Drive.
			return null;
		}
	}
}


text:
package gov.samhsa.acs.c32.wsclient;

import gov.samhsa.acs.common.cxf.AbstractCXFLoggingConfigurerClient;
import gov.samhsa.schemas.c32service.C32Service;
import gov.samhsa.schemas.c32service.C32Service.IC32ServiceProxy;

import java.net.URL;
import java.util.Date;

import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * The Class C32WebServiceClient.
 */
public class C32WebServiceClient extends AbstractCXFLoggingConfigurerClient {

	/** The logger. */
	private final Logger logger = LoggerFactory
			.getLogger(C32WebServiceClient.class);

	/** The endpoint address. */
	private final String endpointAddress;

	/**
	 * Instantiates a new c32 web service client.
	 *
	 * @param endpointAddress
	 *            the endpoint address
	 */
	public C32WebServiceClient(String endpointAddress) {
		this.endpointAddress = endpointAddress;
	}

	/**
	 * Gets the c32.
	 *
	 * @param patientId
	 *            the patient id
	 * @return the c32
	 */
	public String getC32(String patientId) {
		try (IC32ServiceProxy port = createPort(this.endpointAddress)) {
			return port.getC32(patientId);
		} catch (final Exception e) {
			throw toC32WebServiceClientException(e);
		}
	}

	/**
	 * Creates the port.
	 *
	 * @return the i c32 service proxy
	 */
	private IC32ServiceProxy createPort() {
		return configurePort(this::createPortProxy);
	}

	/**
	 * Creates the port.
	 *
	 * @param endpointAddress
	 *            the endpoint address
	 * @return the i c32 service proxy
	 */
	private IC32ServiceProxy createPort(String endpointAddress) {
		return configurePort(() -> createPortProxy(endpointAddress));
	}

	/**
	 * Creates the port proxy.
	 *
	 * @return the i c32 service proxy
	 */
	private IC32ServiceProxy createPortProxy() {
		final URL WSDL_LOCATION = this.getClass().getClassLoader()
				.getResource("C32Service.wsdl");
		final QName SERVICE = new QName("http://schemas.samhsa.gov/c32service",
				"C32Service");

		final IC32ServiceProxy port = new C32Service(WSDL_LOCATION, SERVICE)
				.getBasicHttpBindingIC32Service();
		return port;
	}

	/**
	 * Creates the port.
	 *
	 * @param endpointAddress
	 *            the endpoint address
	 * @return the i c32 service
	 */
	private IC32ServiceProxy createPortProxy(String endpointAddress) {
		final IC32ServiceProxy port = createPort();
		if (StringUtils.hasText(endpointAddress)) {
			final BindingProvider bp = port;
			bp.getRequestContext().put(
					BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);
		}
		return port;
	}

	/**
	 * Run.
	 *
	 * @param patientId
	 *            the patient id
	 */
	private void run(String patientId) {
		// Get a reference to the SOAP service interface.
		try (IC32ServiceProxy port = createPort()) {
			// Add the certificate that is not accepted to your key store and
			// tell your Java/socket factory to use this "trust store"
			// System.setProperty( "javax.net.ssl.trustStore",
			// "C:\\DS4P\\jssecacerts" );
			// System.setProperty( "javax.net.ssl.trustStorePassword", "" );

			// Or turn off SSL check
			// XTrustProvider.install();

			logger.debug("Creating C32 service instance ...");
			long start = new Date().getTime();

			long end = new Date().getTime();
			logger.debug("...Done! IC32Service instance: {}", port);
			logger.debug(
					"Time required to initialize c32 service interface: {} seconds",
					(end - start) / 1000f);

			start = new Date().getTime();

			// String c32 = getC32("http://localhost/Rem.Web/C32Service.svc",
			// patientId);
			// String c32 =
			// getC32("http://taolinpc2.fei.local/Rem.Web/C32Service.svc",
			// patientId);
			final String c32 = port.getC32(patientId);
			end = new Date().getTime();
			logger.debug("Time required to invoke 'getC32': {} seconds",
					(end - start) / 1000f);

			System.out.print(c32);
			logger.debug("");
			logger.debug("Program complete, exiting");
		} catch (final Exception e) {
			logger.error("An exception occurred, exiting", e);
			throw toC32WebServiceClientException(e);
		}
	}

	/**
	 * To c32 web service client exception.
	 *
	 * @param exception
	 *            the exception
	 * @return the c32 web service client exception
	 */
	private C32WebServiceClientException toC32WebServiceClientException(
			Exception exception) {
		logger.error("Error closing C32WebServiceClient port");
		logger.error(exception.getMessage(), exception);
		return new C32WebServiceClientException(exception);
	}

	/**
	 * The main method.
	 *
	 * @param args
	 *            the arguments
	 */
	public static void main(String[] args) {
		final String patientId = "PUI100010060001";
		/*
		 * if (args.length != 1) {
		 * System.out.println("Usage: C32Service <patient id>");
		 * System.exit(-1); }
		 */

		final C32WebServiceClient c32Service = new C32WebServiceClient(null);
		// String patientId = args[0];
		c32Service.run(patientId);
	}
}


text:
namespace AirportSystem.Contracts.Models
{
    public interface IModel
    {
        int Id { get; set; }

        string Name { get; set; }

        int Seats { get; set; }
    }
}


text:
<?php
declare(strict_types=1);

namespace Cake\Console\Exception;

use Cake\Core\Exception\Exception;

/**
 * Used when a Helper cannot be found.
 */
class MissingHelperException extends Exception
{
    /**
     * @var string
     */
    protected $_messageTemplate = 'Helper class %s could not be found.';
}


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2022 Ryo Suzuki
//	Copyright (c) 2016-2022 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include "../Common.hpp"
# include "../2DShapes.hpp"
# include "../PredefinedYesNo.hpp"
# include "P2Fwd.hpp"
# include "P2Shape.hpp"

namespace s3d
{
	class P2Line : public P2Shape
	{
	public:

		SIV3D_NODISCARD_CXX20
		P2Line(b2Body& body, const Line& localPos, OneSided oneSided, const P2Material& material, const P2Filter& filter);

		[[nodiscard]]
		P2ShapeType getShapeType() const noexcept override;

		[[nodiscard]]
		bool isOneSided() const noexcept;

		const P2Shape& draw(const ColorF& color = Palette::White) const override;

		const P2Shape& drawFrame(double thickness, const ColorF& color = Palette::White) const override;

		const P2Shape& drawWireframe(double thickness, const ColorF& color = Palette::White) const override;

		[[nodiscard]]
		Line getLine() const;

	private:

		std::unique_ptr<b2EdgeShape> m_pShape;

		bool m_oneSided = false;
	};
}


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.google.protobuf;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;

/** Schema used for proto2 messages using message_set_wireformat. */
@CheckReturnValue
final class MessageSetSchema<T> implements Schema<T> {
  private final MessageLite defaultInstance;
  private final UnknownFieldSchema<?, ?> unknownFieldSchema;
  private final boolean hasExtensions;
  private final ExtensionSchema<?> extensionSchema;

  private MessageSetSchema(
      UnknownFieldSchema<?, ?> unknownFieldSchema,
      ExtensionSchema<?> extensionSchema,
      MessageLite defaultInstance) {
    this.unknownFieldSchema = unknownFieldSchema;
    this.hasExtensions = extensionSchema.hasExtensions(defaultInstance);
    this.extensionSchema = extensionSchema;
    this.defaultInstance = defaultInstance;
  }

  static <T> MessageSetSchema<T> newSchema(
      UnknownFieldSchema<?, ?> unknownFieldSchema,
      ExtensionSchema<?> extensionSchema,
      MessageLite defaultInstance) {
    return new MessageSetSchema<T>(unknownFieldSchema, extensionSchema, defaultInstance);
  }

  @SuppressWarnings("unchecked")
  @Override
  public T newInstance() {
    return (T) defaultInstance.newBuilderForType().buildPartial();
  }

  @Override
  public boolean equals(T message, T other) {
    Object messageUnknown = unknownFieldSchema.getFromMessage(message);
    Object otherUnknown = unknownFieldSchema.getFromMessage(other);
    if (!messageUnknown.equals(otherUnknown)) {
      return false;
    }
    if (hasExtensions) {
      FieldSet<?> messageExtensions = extensionSchema.getExtensions(message);
      FieldSet<?> otherExtensions = extensionSchema.getExtensions(other);
      return messageExtensions.equals(otherExtensions);
    }
    return true;
  }

  @Override
  public int hashCode(T message) {
    int hashCode = unknownFieldSchema.getFromMessage(message).hashCode();
    if (hasExtensions) {
      FieldSet<?> extensions = extensionSchema.getExtensions(message);
      hashCode = (hashCode * 53) + extensions.hashCode();
    }
    return hashCode;
  }

  @Override
  public void mergeFrom(T message, T other) {
    SchemaUtil.mergeUnknownFields(unknownFieldSchema, message, other);
    if (hasExtensions) {
      SchemaUtil.mergeExtensions(extensionSchema, message, other);
    }
  }

  @SuppressWarnings("unchecked")
  @Override
  public void writeTo(T message, Writer writer) throws IOException {
    FieldSet<?> extensions = extensionSchema.getExtensions(message);
    Iterator<?> iterator = extensions.iterator();
    while (iterator.hasNext()) {
      Entry<?, ?> extension = (Entry<?, ?>) iterator.next();
      FieldSet.FieldDescriptorLite<?> fd = (FieldSet.FieldDescriptorLite<?>) extension.getKey();
      if (fd.getLiteJavaType() != WireFormat.JavaType.MESSAGE || fd.isRepeated() || fd.isPacked()) {
        throw new IllegalStateException("Found invalid MessageSet item.");
      }
      if (extension instanceof LazyField.LazyEntry) {
        writer.writeMessageSetItem(
            fd.getNumber(), ((LazyField.LazyEntry) extension).getField().toByteString());
      } else {
        writer.writeMessageSetItem(fd.getNumber(), extension.getValue());
      }
    }
    writeUnknownFieldsHelper(unknownFieldSchema, message, writer);
  }

  /**
   * A helper method for wildcard capture of {@code unknownFieldSchema}. See:
   * https://docs.oracle.com/javase/tutorial/java/generics/capture.html
   */
  private <UT, UB> void writeUnknownFieldsHelper(
      UnknownFieldSchema<UT, UB> unknownFieldSchema, T message, Writer writer) throws IOException {
    unknownFieldSchema.writeAsMessageSetTo(unknownFieldSchema.getFromMessage(message), writer);
  }

  @SuppressWarnings("ReferenceEquality")
  @Override
  public void mergeFrom(
      T message, byte[] data, int position, int limit, ArrayDecoders.Registers registers)
      throws IOException {
    UnknownFieldSetLite unknownFields = ((GeneratedMessageLite) message).unknownFields;
    if (unknownFields == UnknownFieldSetLite.getDefaultInstance()) {
      unknownFields = UnknownFieldSetLite.newInstance();
      ((GeneratedMessageLite) message).unknownFields = unknownFields;
    }
    final FieldSet<GeneratedMessageLite.ExtensionDescriptor> extensions =
        ((GeneratedMessageLite.ExtendableMessage<?, ?>) message).ensureExtensionsAreMutable();
    GeneratedMessageLite.GeneratedExtension<?, ?> extension = null;
    while (position < limit) {
      position = ArrayDecoders.decodeVarint32(data, position, registers);
      final int startTag = registers.int1;
      if (startTag != WireFormat.MESSAGE_SET_ITEM_TAG) {
        if (WireFormat.getTagWireType(startTag) == WireFormat.WIRETYPE_LENGTH_DELIMITED) {
          extension =
              (GeneratedMessageLite.GeneratedExtension<?, ?>) extensionSchema.findExtensionByNumber(
                  registers.extensionRegistry, defaultInstance,
                  WireFormat.getTagFieldNumber(startTag));
          if (extension != null) {
            position =
                ArrayDecoders.decodeMessageField(
                    Protobuf.getInstance().schemaFor(
                        extension.getMessageDefaultInstance().getClass()),
                    data, position, limit, registers);
            extensions.setField(extension.descriptor, registers.object1);
          } else {
            position =
                ArrayDecoders.decodeUnknownField(
                    startTag, data, position, limit, unknownFields, registers);
          }
        } else {
          position = ArrayDecoders.skipField(startTag, data, position, limit, registers);
        }
        continue;
      }

      int typeId = 0;
      ByteString rawBytes = null;

      while (position < limit) {
        position = ArrayDecoders.decodeVarint32(data, position, registers);
        final int tag = registers.int1;
        final int number = WireFormat.getTagFieldNumber(tag);
        final int wireType = WireFormat.getTagWireType(tag);
        switch (number) {
          case WireFormat.MESSAGE_SET_TYPE_ID:
            if (wireType == WireFormat.WIRETYPE_VARINT) {
              position = ArrayDecoders.decodeVarint32(data, position, registers);
              typeId = registers.int1;
              extension =
                  (GeneratedMessageLite.GeneratedExtension<?, ?>) extensionSchema
                      .findExtensionByNumber(registers.extensionRegistry, defaultInstance, typeId);
              continue;
            }
            break;
          case WireFormat.MESSAGE_SET_MESSAGE:
            if (extension != null) {
              position = ArrayDecoders.decodeMessageField(
                  Protobuf.getInstance().schemaFor(
                      extension.getMessageDefaultInstance().getClass()),
                  data, position, limit, registers);
              extensions.setField(extension.descriptor, registers.object1);
              continue;
            } else {
              if (wireType == WireFormat.WIRETYPE_LENGTH_DELIMITED) {
                position = ArrayDecoders.decodeBytes(data, position, registers);
                rawBytes = (ByteString) registers.object1;
                continue;
              }
              break;
            }
          default:
            break;
        }
        if (tag == WireFormat.MESSAGE_SET_ITEM_END_TAG) {
          break;
        }
        position = ArrayDecoders.skipField(tag, data, position, limit, registers);
      }

      if (rawBytes != null) {
        unknownFields.storeField(
            WireFormat.makeTag(typeId, WireFormat.WIRETYPE_LENGTH_DELIMITED), rawBytes);
      }
    }
    if (position != limit) {
      throw InvalidProtocolBufferException.parseFailure();
    }
  }

  @Override
  public void mergeFrom(T message, Reader reader, ExtensionRegistryLite extensionRegistry)
      throws IOException {
    mergeFromHelper(unknownFieldSchema, extensionSchema, message, reader, extensionRegistry);
  }

  /**
   * A helper method for wildcard capture of {@code unknownFieldSchema}. See:
   * https://docs.oracle.com/javase/tutorial/java/generics/capture.html
   */
  private <UT, UB, ET extends FieldSet.FieldDescriptorLite<ET>> void mergeFromHelper(
      UnknownFieldSchema<UT, UB> unknownFieldSchema,
      ExtensionSchema<ET> extensionSchema,
      T message,
      Reader reader,
      ExtensionRegistryLite extensionRegistry)
      throws IOException {
    UB unknownFields = unknownFieldSchema.getBuilderFromMessage(message);
    FieldSet<ET> extensions = extensionSchema.getMutableExtensions(message);
    try {
      while (true) {
        final int number = reader.getFieldNumber();
        if (number == Reader.READ_DONE) {
          return;
        }
        if (parseMessageSetItemOrUnknownField(
            reader,
            extensionRegistry,
            extensionSchema,
            extensions,
            unknownFieldSchema,
            unknownFields)) {
          continue;
        }
        // Done reading.
        return;
      }
    } finally {
      unknownFieldSchema.setBuilderToMessage(message, unknownFields);
    }
  }

  @Override
  public void makeImmutable(T message) {
    unknownFieldSchema.makeImmutable(message);
    extensionSchema.makeImmutable(message);
  }

  private <UT, UB, ET extends FieldSet.FieldDescriptorLite<ET>>
      boolean parseMessageSetItemOrUnknownField(
          Reader reader,
          ExtensionRegistryLite extensionRegistry,
          ExtensionSchema<ET> extensionSchema,
          FieldSet<ET> extensions,
          UnknownFieldSchema<UT, UB> unknownFieldSchema,
          UB unknownFields)
          throws IOException {
    int startTag = reader.getTag();
    if (startTag != WireFormat.MESSAGE_SET_ITEM_TAG) {
      if (WireFormat.getTagWireType(startTag) == WireFormat.WIRETYPE_LENGTH_DELIMITED) {
        Object extension =
            extensionSchema.findExtensionByNumber(
                extensionRegistry, defaultInstance, WireFormat.getTagFieldNumber(startTag));
        if (extension != null) {
          extensionSchema.parseLengthPrefixedMessageSetItem(
              reader, extension, extensionRegistry, extensions);
          return true;
        } else {
          return unknownFieldSchema.mergeOneFieldFrom(unknownFields, reader);
        }
      } else {
        return reader.skipField();
      }
    }

    // The wire format for MessageSet is:
    //   message MessageSet {
    //     repeated group Item = 1 {
    //       required uint32 typeId = 2;
    //       required bytes message = 3;
    //     }
    //   }
    // "typeId" is the extension's field number.  The extension can only be
    // a message type, where "message" contains the encoded bytes of that
    // message.
    //
    // In practice, we will probably never see a MessageSet item in which
    // the message appears before the type ID, or where either field does not
    // appear exactly once.  However, in theory such cases are valid, so we
    // should be prepared to accept them.

    int typeId = 0;
    ByteString rawBytes = null; // If we encounter "message" before "typeId"
    Object extension = null;

    // Read bytes from input, if we get it's type first then parse it eagerly,
    // otherwise we store the raw bytes in a local variable.
    loop:
    while (true) {
      final int number = reader.getFieldNumber();
      if (number == Reader.READ_DONE) {
        break;
      }

      final int tag = reader.getTag();
      if (tag == WireFormat.MESSAGE_SET_TYPE_ID_TAG) {
        typeId = reader.readUInt32();
        extension =
            extensionSchema.findExtensionByNumber(extensionRegistry, defaultInstance, typeId);
        continue;
      } else if (tag == WireFormat.MESSAGE_SET_MESSAGE_TAG) {
        if (extension != null) {
          extensionSchema.parseLengthPrefixedMessageSetItem(
              reader, extension, extensionRegistry, extensions);
          continue;
        }
        // We haven't seen a type ID yet or we want parse message lazily.
        rawBytes = reader.readBytes();
        continue;
      } else {
        if (!reader.skipField()) {
          break loop; // End of group
        }
      }
    }

    if (reader.getTag() != WireFormat.MESSAGE_SET_ITEM_END_TAG) {
      throw InvalidProtocolBufferException.invalidEndTag();
    }

    // If there are any rawBytes left, it means the message content appears before the type ID.
    if (rawBytes != null) {
      if (extension != null) { // We known the type
        // TODO(xiaofeng): Instead of reading into a temporary ByteString, maybe there is a way
        // to read directly from Reader to the submessage?
        extensionSchema.parseMessageSetItem(rawBytes, extension, extensionRegistry, extensions);
      } else {
        unknownFieldSchema.addLengthDelimited(unknownFields, typeId, rawBytes);
      }
    }
    return true;
  }

  @Override
  public final boolean isInitialized(T message) {
    FieldSet<?> extensions = extensionSchema.getExtensions(message);
    return extensions.isInitialized();
  }

  @Override
  public int getSerializedSize(T message) {
    int size = 0;

    size += getUnknownFieldsSerializedSize(unknownFieldSchema, message);

    if (hasExtensions) {
      size += extensionSchema.getExtensions(message).getMessageSetSerializedSize();
    }

    return size;
  }

  private <UT, UB> int getUnknownFieldsSerializedSize(
      UnknownFieldSchema<UT, UB> schema, T message) {
    UT unknowns = schema.getFromMessage(message);
    return schema.getSerializedSizeAsMessageSet(unknowns);
  }
}


text:
var hoodie = new Hoodie();

var models = {};

models.ReadDateModel = hoodie.backbone.Model.extend({
  type: 'read-date',
  dateStarted: null,
  progress: 0,
  dateEnded: null
});

models.ReadDateCollection = hoodie.backbone.Collection.extend({
  model: models.ReadDateModel
});

models.TagModel = hoodie.backbone.Model.extend({
  type: 'tag',
  defaults: {
    name: null,
    dateAdded: moment(),
  }
});

models.TagCollection = hoodie.backbone.Collection.extend({
  model: models.TagModel
});

models.LinkModel = hoodie.backbone.Model.extend({
  type: 'link',
  name: null,
  url: null,
  dateAdded: null,
});

models.LinkCollection = hoodie.backbone.Collection.extend({
  model: models.LinkModel
});

models.BookModel = hoodie.backbone.Model.extend({
  type: 'book',
  defaults: {
    notes: null,
    isbn10: null,
    isbn13: null,
    rating: null,
    authors: null,
    title: '',
    tags: new models.TagCollection(),
    readDates: new models.ReadDateCollection(),
    links: new models.LinkCollection()
  }
  // constructor: function() {
  //   this.readDates = new models.ReadDateCollection();
  //   this.tags = new models.TagCollection();
  //   this.links = new models.LinkCollection();
  //   Backbone.Model.apply(this, arguments);
  // }

});

models.BookCollection = hoodie.backbone.Collection.extend({
  model: models.BookModel
});

module.exports = models;