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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../../../style.css" type="text/css" media="screen">
<link rel="stylesheet" href="../../../../print.css" type="text/css" media="print">
<meta content="OAuthConnection,net.yahoo.fireeagle.oauth.OAuthConnection,_callback,_consumer,_httpMethod,_postArgs,_signatureMethod,_token,_url,_urlArgs,callback,consumer,postArgs,signatureMethod,token,url,asyncRequest,encodeVars,filterOAuthParams,makeUrlParams,setupGet,setupPost,signRequest,updateToken" name="keywords">
<title>net.yahoo.fireeagle.oauth.OAuthConnection</title>

Fire Eagle API AS3 library	All Packages | All Classes | Index | FramesNo Frames

Class OAuthConnection	Properties | Methods

Package	net.yahoo.fireeagle.oauth

Class	public class OAuthConnection

  A utility class that is used to create and handle basic OAuth HTTP requests in Flash and AIR.
  It uses the OAuth lib and Connection from the
  Y!OS AS3 library

  Available callback functions are:

security

open

progress

failure

success

httpStatus (Adobe AIR only)

Example

  var args:Object = new Object();
  args.foo = "bar";
  args.format = "xml";

  var callback:Object = new Object();
  callback.success = handleSuccess;
  callback.failure = handleFailure;

  var connection:OAuthConnection = new OAuthConnection(consumerKey, consumerSecret, accessKey, accessSecret);

  connection.setupGet("http://example.com/some_feed.xml", callback, args);

  connection.asyncRequest();

  function handleSuccess(response:Object):void
  {
   trace(response.responseText);
   var xml:XML = response.responseXML; // grab the parsed xml object.
  }

  function handleFailure(response:Object):void
  {
   trace(response.responseText);
  }

See also

com.yahoo.net.Connection

Public Properties

 	Property	Defined by

 	 	callback : Object
[read-only]
   Returns the callback object for this connection.

	OAuthConnection

 	 	consumer : OAuthConsumer
[read-only]
   Returns the OAuthConsumer for this connection.

	OAuthConnection

 	 	postArgs : String
[read-only]
   Returns the encoded POST vars for this connection.

	OAuthConnection

 	 	signatureMethod : IOAuthSignatureMethod

   Returns OAuth signature method implementation.

	OAuthConnection

 	 	token : OAuthToken
[read-only]
   Returns the OAuthToken for this connection.

	OAuthConnection

 	 	url : String
[read-only]
   Returns the signed and encoded url for this connection.

	OAuthConnection

Protected Properties

 	Property	Defined by

 	 	_callback : Object

	OAuthConnection

 	 	_consumer : OAuthConsumer

	OAuthConnection

 	 	_httpMethod : String = ""

	OAuthConnection

 	 	_postArgs : String = ""

	OAuthConnection

 	 	_signatureMethod : IOAuthSignatureMethod

	OAuthConnection

 	 	_token : OAuthToken

	OAuthConnection

 	 	_url : String = ""

	OAuthConnection

 	 	_urlArgs : Object = null

	OAuthConnection

Public Methods

 	Method	Defined by

OAuthConnection(consumerKey:String, consumerSecret:String, oauthKey:String = null, oauthSecret:String = null)

   Class constructor.

	OAuthConnection

asyncRequest():void

   Sends the HTTP request previously set up with a call to setupGet or setupPost.

	OAuthConnection

setupGet(url:String, callback:Object, args:Object = null):void

   Sets up a HTTP GET request method, url and arg for a signed OAuth request.

	OAuthConnection

setupPost(url:String, callback:Object, args:Object = null):void

   Sets up a HTTP POST request method, url and arg for a signed OAuth request.

	OAuthConnection

updateToken(oauthKey:String = null, oauthSecret:String = null):void

   Swaps out the OAuthToken for this connection using the credentials passed in.

	OAuthConnection

Protected Methods

 	Method	Defined by

encodeVars(args:Object):Object

[static]
   URI encodes the args keys and properties.

	OAuthConnection

filterOAuthParams(args:Object, returnOAuthParams:Boolean):Object

[static]
   Filters out either the non-OAuth properties of args, or the OAuth properties.

	OAuthConnection

makeUrlParams(args:Object):String

[static]
   Converts name/value pair args to a String ready to append as url parameters.

	OAuthConnection

signRequest(httpMethod:String, url:String, args:Object = null):void

   Signs the request using the method, url, args, OAuthConsumer and OAuthToken.

	OAuthConnection

Property detail

_callback	property

protected var _callback:Object

callback	property

callback:Object  [read-only]

   Returns the callback object for this connection.

Implementation

    public function get callback():Object

_consumer	property

protected var _consumer:OAuthConsumer

consumer	property

consumer:OAuthConsumer  [read-only]

   Returns the OAuthConsumer for this connection.

Implementation

    public function get consumer():OAuthConsumer

_httpMethod	property

protected var _httpMethod:String = ""

_postArgs	property

protected var _postArgs:String = ""

postArgs	property

postArgs:String  [read-only]

   Returns the encoded POST vars for this connection.
   Valid after a call to setupGet or setupPost.

Implementation

    public function get postArgs():String

_signatureMethod	property

protected var _signatureMethod:IOAuthSignatureMethod

signatureMethod	property

signatureMethod:IOAuthSignatureMethod  [read-write]

   Returns OAuth signature method implementation.

Implementation

    public function get signatureMethod():IOAuthSignatureMethod

    public function set signatureMethod(value:IOAuthSignatureMethod):void

_token	property

protected var _token:OAuthToken

token	property

token:OAuthToken  [read-only]

   Returns the OAuthToken for this connection.

Implementation

    public function get token():OAuthToken

_url	property

protected var _url:String = ""

url	property

url:String  [read-only]

   Returns the signed and encoded url for this connection.
   Valid after a call to setupGet or setupPost.

Implementation

    public function get url():String

_urlArgs	property

protected var _urlArgs:Object = null

Constructor detail

OAuthConnection	()	constructor

public function OAuthConnection(consumerKey:String, consumerSecret:String, oauthKey:String = null, oauthSecret:String = null)

   Class constructor.
   Creates a new OAuthConnection object for the provided credentials.

Parameters

	consumerKey:String —  The OAuth consumer key string to use for this connection.

	consumerSecret:String — The OAuth consumer secret string to use for this connection.

	oauthKey:String (default = null) —   An OAuth general or access key string to use for this connection, optional.

	oauthSecret:String (default = null) —  An OAuth general or access secret string to use for this connection, optional.

Throws

	 — Throws an Error if the consumer key or secret is empty.

Method detail

asyncRequest	()	method

public function asyncRequest():void

   Sends the HTTP request previously set up with a call to setupGet or setupPost.

encodeVars	()	method

protected static function encodeVars(args:Object):Object

   URI encodes the args keys and properties.

Parameters

	args:Object —    Name/value pairs to be encoded.

Returns

	Object —     Encoded name/value pairs.

See also

encodeURIComponent

filterOAuthParams	()	method

protected static function filterOAuthParams(args:Object, returnOAuthParams:Boolean):Object

   Filters out either the non-OAuth properties of args, or the OAuth properties.

Parameters

	args:Object —    Name/value pairs to be filtered.

	returnOAuthParams:Boolean —    Boolean if true returns the OAuth name/value pairs only, false all others.

Returns

	Object —     Depending on the oAuth param either returns the OAuth name/value pairs or all others.

makeUrlParams	()	method

protected static function makeUrlParams(args:Object):String

   Converts name/value pair args to a String ready to append as url parameters.

Parameters

	args:Object —    Name/value pairs to be converted to url param string.

Returns

	String —     The url parameter string without a '?'.

setupGet	()	method

public function setupGet(url:String, callback:Object, args:Object = null):void

   Sets up a HTTP GET request method, url and arg for a signed OAuth request. Call this before accessing
   url or args.

Parameters

	url:String —   The base url without url parameters to use for this request.

	callback:Object —  The callback object for this request.

	args:Object (default = null) —   The arguments for this request, as name/value pairs.

setupPost	()	method

public function setupPost(url:String, callback:Object, args:Object = null):void

   Sets up a HTTP POST request method, url and arg for a signed OAuth request. Call this before accessing
   url or args.

Parameters

	url:String —   The base url without url parameters to use for this request.

	callback:Object —  The callback object for this request.

	args:Object (default = null) —   The arguments for this request, as name/value pairs.

signRequest	()	method

protected function signRequest(httpMethod:String, url:String, args:Object = null):void

   Signs the request using the method, url, args, OAuthConsumer and OAuthToken.

Parameters

	httpMethod:String —  "GET" or "POST": URLRequestMethod.GET, URLRequestMethod.POST.

	url:String —    The base url without url parameters to use for this request.

	args:Object (default = null) —    The arguments for this request, as name/value pairs.

Throws

	 — Throws an Error if the request cannot be signed.

See also

com.yahoo.oauth.OAuthRequest

updateToken	()	method

public function updateToken(oauthKey:String = null, oauthSecret:String = null):void

   Swaps out the OAuthToken for this connection using the credentials passed in.
   If no credentials are passed in, clears the OAuthToken for this connection.

Parameters

	oauthKey:String (default = null) —   An OAuth general or access key string to use for this connection, optional.

	oauthSecret:String (default = null) —  An OAuth general or access secret string to use for this connection, optional.


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/*
 * nsBaseContentList is a basic list of content nodes; nsContentList
 * is a commonly used NodeList implementation (used for
 * getElementsByTagName, some properties on nsIDOMHTMLDocument, etc).
 */

#ifndef nsContentList_h___
#define nsContentList_h___

#include "nsISupports.h"
#include "nsCOMArray.h"
#include "nsString.h"
#include "nsIHTMLCollection.h"
#include "nsIDOMNodeList.h"
#include "nsINodeList.h"
#include "nsStubMutationObserver.h"
#include "nsIAtom.h"
#include "nsINameSpaceManager.h"
#include "nsCycleCollectionParticipant.h"
#include "nsWrapperCache.h"
#include "nsCRT.h"
#include "mozilla/dom/Element.h"

// Magic namespace id that means "match all namespaces".  This is
// negative so it won't collide with actual namespace constants.
#define kNameSpaceID_Wildcard PR_INT32_MIN

// This is a callback function type that can be used to implement an
// arbitrary matching algorithm.  aContent is the content that may
// match the list, while aNamespaceID, aAtom, and aData are whatever
// was passed to the list's constructor.
typedef PRBool (*nsContentListMatchFunc)(nsIContent* aContent,
                                         PRInt32 aNamespaceID,
                                         nsIAtom* aAtom,
                                         void* aData);

typedef void (*nsContentListDestroyFunc)(void* aData);

class nsIDocument;
class nsIDOMHTMLFormElement;

class nsBaseContentList : public nsINodeList
{
public:
  virtual ~nsBaseContentList();

  NS_DECL_CYCLE_COLLECTING_ISUPPORTS

  // nsIDOMNodeList
  NS_DECL_NSIDOMNODELIST

  // nsINodeList
  virtual nsIContent* GetNodeAt(PRUint32 aIndex);
  virtual PRInt32 IndexOf(nsIContent* aContent);

  PRUint32 Length() const {
    return mElements.Count();
  }

  NS_DECL_CYCLE_COLLECTION_CLASS_AMBIGUOUS(nsBaseContentList, nsINodeList)

  void AppendElement(nsIContent *aContent);
  void MaybeAppendElement(nsIContent* aContent)
  {
    if (aContent)
      AppendElement(aContent);
  }

  /**
   * Insert the element at a given index, shifting the objects at
   * the given index and later to make space.
   * @param aContent Element to insert, must not be null
   * @param aIndex Index to insert the element at.
   */
  void InsertElementAt(nsIContent* aContent, PRInt32 aIndex);

  void RemoveElement(nsIContent *aContent);

  void Reset() {
    mElements.Clear();
  }

  virtual PRInt32 IndexOf(nsIContent *aContent, PRBool aDoFlush);

protected:
  nsCOMArray<nsIContent> mElements;
};

// This class is used only by form element code and this is a static
// list of elements. NOTE! This list holds strong references to
// the elements in the list.
class nsFormContentList : public nsBaseContentList
{
public:
  nsFormContentList(nsIDOMHTMLFormElement *aForm,
                    nsBaseContentList& aContentList);
};

/**
 * Class that's used as the key to hash nsContentList implementations
 * for fast retrieval
 */
class nsContentListKey
{
public:
  nsContentListKey(nsINode* aRootNode,
                   nsIAtom* aHTMLMatchAtom,
                   nsIAtom* aXMLMatchAtom,
                   PRInt32 aMatchNameSpaceId)
    : mHTMLMatchAtom(aHTMLMatchAtom),
      mXMLMatchAtom(aXMLMatchAtom),
      mMatchNameSpaceId(aMatchNameSpaceId),
      mRootNode(aRootNode)
  {
    NS_ASSERTION(!aXMLMatchAtom == !aHTMLMatchAtom, "Either neither or both atoms should be null");
  }

  nsContentListKey(const nsContentListKey& aContentListKey)
    : mHTMLMatchAtom(aContentListKey.mHTMLMatchAtom),
      mXMLMatchAtom(aContentListKey.mXMLMatchAtom),
      mMatchNameSpaceId(aContentListKey.mMatchNameSpaceId),
      mRootNode(aContentListKey.mRootNode)
  {
  }

  PRBool Equals(const nsContentListKey& aContentListKey) const
  {
    NS_ASSERTION(mHTMLMatchAtom == aContentListKey.mHTMLMatchAtom
                 || mXMLMatchAtom != aContentListKey.mXMLMatchAtom, "HTML atoms should match if XML atoms match");

    return
      mXMLMatchAtom == aContentListKey.mXMLMatchAtom &&
      mMatchNameSpaceId == aContentListKey.mMatchNameSpaceId &&
      mRootNode == aContentListKey.mRootNode;
  }

  inline PRUint32 GetHash(void) const
  {
    return
      NS_PTR_TO_INT32(mXMLMatchAtom.get()) ^
      (NS_PTR_TO_INT32(mRootNode) << 12) ^
      (mMatchNameSpaceId << 24);
  }

protected:
  nsCOMPtr<nsIAtom> mHTMLMatchAtom;
  nsCOMPtr<nsIAtom> mXMLMatchAtom;
  PRInt32 mMatchNameSpaceId;
  nsINode* mRootNode; // Weak ref
};

/**
 * LIST_UP_TO_DATE means that the list is up to date and need not do
 * any walking to be able to answer any questions anyone may have.
 */
#define LIST_UP_TO_DATE 0
/**
 * LIST_DIRTY means that the list contains no useful information and
 * if anyone asks it anything it will have to populate itself before
 * answering.
 */
#define LIST_DIRTY 1
/**
 * LIST_LAZY means that the list has populated itself to a certain
 * extent and that that part of the list is still valid.  Requests for
 * things outside that part of the list will require walking the tree
 * some more.  When a list is in this state, the last thing in
 * mElements is the last node in the tree that the list looked at.
 */
#define LIST_LAZY 2

/**
 * Class that implements a live NodeList that matches Elements in the
 * tree based on some criterion.
 */
class nsContentList : public nsBaseContentList,
                      protected nsContentListKey,
                      public nsIHTMLCollection,
                      public nsStubMutationObserver,
                      public nsWrapperCache
{
public:
  NS_DECL_ISUPPORTS_INHERITED

  /**
   * @param aRootNode The node under which to limit our search.
   * @param aMatchAtom An atom whose meaning depends on aMatchNameSpaceId.
   *                   The special value "*" always matches whatever aMatchAtom
   *                   is matched against.
   * @param aMatchNameSpaceId If kNameSpaceID_Unknown, then aMatchAtom is the
   *                          tagName to match.
   *                          If kNameSpaceID_Wildcard, then aMatchAtom is the
   *                          localName to match.
   *                          Otherwise we match nodes whose namespace is
   *                          aMatchNameSpaceId and localName matches
   *                          aMatchAtom.
   * @param aDeep If false, then look only at children of the root, nothing
   *              deeper.  If true, then look at the whole subtree rooted at
   *              our root.
   */
  nsContentList(nsINode* aRootNode,
                PRInt32 aMatchNameSpaceId,
                nsIAtom* aHTMLMatchAtom,
                nsIAtom* aXMLMatchAtom,
                PRBool aDeep = PR_TRUE);

  /**
   * @param aRootNode The node under which to limit our search.
   * @param aFunc the function to be called to determine whether we match.
   *              This function MUST NOT ever cause mutation of the DOM.
   *              The nsContentList implementation guarantees that everything
   *              passed to the function will be IsElement().
   * @param aDestroyFunc the function that will be called to destroy aData
   * @param aData closure data that will need to be passed back to aFunc
   * @param aDeep If false, then look only at children of the root, nothing
   *              deeper.  If true, then look at the whole subtree rooted at
   *              our root.
   * @param aMatchAtom an atom to be passed back to aFunc
   * @param aMatchNameSpaceId a namespace id to be passed back to aFunc
   * @param aFuncMayDependOnAttr a boolean that indicates whether this list is
   *                             sensitive to attribute changes.
   */
  nsContentList(nsINode* aRootNode,
                nsContentListMatchFunc aFunc,
                nsContentListDestroyFunc aDestroyFunc,
                void* aData,
                PRBool aDeep = PR_TRUE,
                nsIAtom* aMatchAtom = nsnull,
                PRInt32 aMatchNameSpaceId = kNameSpaceID_None,
                PRBool aFuncMayDependOnAttr = PR_TRUE);
  virtual ~nsContentList();

  // nsIDOMHTMLCollection
  NS_DECL_NSIDOMHTMLCOLLECTION

  // nsBaseContentList overrides
  virtual PRInt32 IndexOf(nsIContent *aContent, PRBool aDoFlush);
  virtual nsIContent* GetNodeAt(PRUint32 aIndex);
  virtual PRInt32 IndexOf(nsIContent* aContent);

  // nsIHTMLCollection
  virtual nsIContent* GetNodeAt(PRUint32 aIndex, nsresult* aResult);
  virtual nsISupports* GetNamedItem(const nsAString& aName,
                                    nsWrapperCache** aCache,
                                    nsresult* aResult);

  // nsContentList public methods
  NS_HIDDEN_(nsINode*) GetParentObject() { return mRootNode; }
  NS_HIDDEN_(PRUint32) Length(PRBool aDoFlush);
  NS_HIDDEN_(nsIContent*) Item(PRUint32 aIndex, PRBool aDoFlush);
  NS_HIDDEN_(nsIContent*) NamedItem(const nsAString& aName, PRBool aDoFlush);

  nsContentListKey* GetKey() {
    return static_cast<nsContentListKey*>(this);
  }

  // nsIMutationObserver
  NS_DECL_NSIMUTATIONOBSERVER_ATTRIBUTECHANGED
  NS_DECL_NSIMUTATIONOBSERVER_CONTENTAPPENDED
  NS_DECL_NSIMUTATIONOBSERVER_CONTENTINSERTED
  NS_DECL_NSIMUTATIONOBSERVER_CONTENTREMOVED
  NS_DECL_NSIMUTATIONOBSERVER_NODEWILLBEDESTROYED

  static nsContentList* FromSupports(nsISupports* aSupports)
  {
    nsINodeList* list = static_cast<nsINodeList*>(aSupports);
#ifdef DEBUG
    {
      nsCOMPtr<nsINodeList> list_qi = do_QueryInterface(aSupports);

      // If this assertion fires the QI implementation for the object in
      // question doesn't use the nsINodeList pointer as the nsISupports
      // pointer. That must be fixed, or we'll crash...
      NS_ASSERTION(list_qi == list, "Uh, fix QI!");
    }
#endif
    return static_cast<nsContentList*>(list);
  }

protected:
  /**
   * Returns whether the element matches our criterion
   *
   * @param  aElement the element to attempt to match
   * @return whether we match
   */
  PRBool Match(mozilla::dom::Element *aElement);
  /**
   * See if anything in the subtree rooted at aContent, including
   * aContent itself, matches our criterion.
   *
   * @param  aContent the root of the subtree to match against
   * @return whether we match something in the tree rooted at aContent
   */
  PRBool MatchSelf(nsIContent *aContent);

  /**
   * Populate our list.  Stop once we have at least aNeededLength
   * elements.  At the end of PopulateSelf running, either the last
   * node we examined is the last node in our array or we have
   * traversed the whole document (or both).
   *
   * @param aNeededLength the length the list should have when we are
   *        done (unless it exhausts the document)
   */
  void PopulateSelf(PRUint32 aNeededLength);

  /**
   * @param  aContainer a content node which must be a descendant of
   *         mRootNode
   * @return PR_TRUE if children or descendants of aContainer could match our
   *                 criterion.
   *         PR_FALSE otherwise.
   */
  PRBool MayContainRelevantNodes(nsINode* aContainer)
  {
    return mDeep || aContainer == mRootNode;
  }

  /**
   * Remove ourselves from the hashtable that caches commonly accessed
   * content lists.  Generally done on destruction.
   */
  void RemoveFromHashtable();
  /**
   * If state is not LIST_UP_TO_DATE, fully populate ourselves with
   * all the nodes we can find.
   */
  inline void BringSelfUpToDate(PRBool aDoFlush);

  /**
   * Sets the state to LIST_DIRTY and clears mElements array.
   * @note This is the only acceptable way to set state to LIST_DIRTY.
   */
  void SetDirty()
  {
    mState = LIST_DIRTY;
    Reset();
  }

  /**
   * To be called from non-destructor locations that want to remove from caches.
   * Needed because if subclasses want to have cache behavior they can't just
   * override RemoveFromHashtable(), since we call that in our destructor.
   */
  virtual void RemoveFromCaches() {
    RemoveFromHashtable();
  }

  /**
   * Function to use to determine whether a piece of content matches
   * our criterion
   */
  nsContentListMatchFunc mFunc;
  /**
   * Cleanup closure data with this.
   */
  nsContentListDestroyFunc mDestroyFunc;
  /**
   * Closure data to pass to mFunc when we call it
   */
  void* mData;
  /**
   * True if we are looking for elements named "*"
   */
  PRPackedBool mMatchAll;
  /**
   * The current state of the list (possible values are:
   * LIST_UP_TO_DATE, LIST_LAZY, LIST_DIRTY
   */
  PRUint8 mState;
  /**
   * Whether to actually descend the tree.  If this is false, we won't
   * consider grandkids of mRootNode.
   */
  PRPackedBool mDeep;
  /**
   * Whether the return value of mFunc could depend on the values of
   * attributes.
   */
  PRPackedBool mFuncMayDependOnAttr;

#ifdef DEBUG_CONTENT_LIST
  void AssertInSync();
#endif
};

/**
 * A class of cacheable content list; cached on the combination of aRootNode + aFunc + aDataString
 */
class nsCacheableFuncStringContentList;

class NS_STACK_CLASS nsFuncStringCacheKey {
public:
  nsFuncStringCacheKey(nsINode* aRootNode,
                       nsContentListMatchFunc aFunc,
                       const nsAString& aString) :
    mRootNode(aRootNode),
    mFunc(aFunc),
    mString(aString)
    {}

  PRUint32 GetHash(void) const
  {
    return NS_PTR_TO_INT32(mRootNode) ^ (NS_PTR_TO_INT32(mFunc) << 12) ^
      nsCRT::HashCode(mString.BeginReading(), mString.Length());
  }

private:
  friend class nsCacheableFuncStringContentList;

  nsINode* const mRootNode;
  const nsContentListMatchFunc mFunc;
  const nsAString& mString;
};

/**
 * A function that allocates the matching data for this
 * FuncStringContentList.  Returning aString is perfectly fine; in
 * that case the destructor function should be a no-op.
 */
typedef void* (*nsFuncStringContentListDataAllocator)(nsINode* aRootNode,
                                                      const nsString* aString);

// aDestroyFunc is allowed to be null
class nsCacheableFuncStringContentList : public nsContentList {
public:
  nsCacheableFuncStringContentList(nsINode* aRootNode,
                                   nsContentListMatchFunc aFunc,
                                   nsContentListDestroyFunc aDestroyFunc,
                                   nsFuncStringContentListDataAllocator aDataAllocator,
                                   const nsAString& aString) :
    nsContentList(aRootNode, aFunc, aDestroyFunc, nsnull),
    mString(aString)
  {
    mData = (*aDataAllocator)(aRootNode, &mString);
  }

  virtual ~nsCacheableFuncStringContentList();

  PRBool Equals(const nsFuncStringCacheKey* aKey) {
    return mRootNode == aKey->mRootNode && mFunc == aKey->mFunc &&
      mString == aKey->mString;
  }

  PRBool AllocatedData() const { return !!mData; }
protected:
  virtual void RemoveFromCaches() {
    RemoveFromFuncStringHashtable();
  }
  void RemoveFromFuncStringHashtable();

  nsString mString;
};

already_AddRefed<nsContentList>
NS_GetContentList(nsINode* aRootNode,
                  PRInt32 aMatchNameSpaceId,
                  nsIAtom* aHTMLMatchAtom,
                  nsIAtom* aXMLMatchAtom = nsnull);

already_AddRefed<nsContentList>
NS_GetFuncStringContentList(nsINode* aRootNode,
                            nsContentListMatchFunc aFunc,
                            nsContentListDestroyFunc aDestroyFunc,
                            nsFuncStringContentListDataAllocator aDataAllocator,
                            const nsAString& aString);
#endif // nsContentList_h___

redpajama_set_name: RedPajamaGithub


text:
#ifndef ESP_APP_TRACE_UTIL_H_
#define ESP_APP_TRACE_UTIL_H_

#ifdef __cplusplus
extern "C" {
#endif

#include "freertos/FreeRTOS.h"
#include "esp_err.h"
#include "esp_timer.h"

/** Infinite waiting timeout */
#define ESP_APPTRACE_TMO_INFINITE               ((uint32_t)-1)

/** Structure which holds data necessary for measuring time intervals.
 *
 *  After initialization via esp_apptrace_tmo_init() user needs to call esp_apptrace_tmo_check()
 *  periodically to check timeout for expiration.
 */
typedef struct {
    int64_t   start;   ///< time interval start (in us)
    int64_t   tmo;     ///< timeout value (in us)
    int64_t   elapsed; ///< elapsed time (in us)
} esp_apptrace_tmo_t;

/**
 * @brief Initializes timeout structure.
 *
 * @param tmo       Pointer to timeout structure to be initialized.
 * @param user_tmo  Timeout value (in us). Use ESP_APPTRACE_TMO_INFINITE to wait indefinetly.
*/
static inline void esp_apptrace_tmo_init(esp_apptrace_tmo_t *tmo, uint32_t user_tmo)
{
    tmo->start = esp_timer_get_time();
    tmo->tmo = user_tmo == ESP_APPTRACE_TMO_INFINITE ? (int64_t)-1 : (int64_t)user_tmo;
    tmo->elapsed = 0;
}

/**
 * @brief Checks timeout for expiration.
 *
 * @param tmo Pointer to timeout structure.
 *
 * @return number of remaining us till tmo.
 */
esp_err_t esp_apptrace_tmo_check(esp_apptrace_tmo_t *tmo);

static inline uint32_t esp_apptrace_tmo_remaining_us(esp_apptrace_tmo_t *tmo)
{
    return tmo->tmo != (int64_t)-1 ? (tmo->elapsed - tmo->tmo) : ESP_APPTRACE_TMO_INFINITE;
}

/** Tracing module synchronization lock */
typedef struct {
    spinlock_t mux;
    unsigned int_state;
} esp_apptrace_lock_t;

/**
 * @brief Initializes lock structure.
 *
 * @param lock Pointer to lock structure to be initialized.
 */
static inline void esp_apptrace_lock_init(esp_apptrace_lock_t *lock)
{
    portMUX_INITIALIZE(&lock->mux);
    lock->int_state = 0;
}

/**
 * @brief Tries to acquire lock in specified time period.
 *
 * @param lock Pointer to lock structure.
 * @param tmo  Pointer to timeout struct.
 *
 * @return ESP_OK on success, otherwise \see esp_err_t
 */
esp_err_t esp_apptrace_lock_take(esp_apptrace_lock_t *lock, esp_apptrace_tmo_t *tmo);

/**
 * @brief Releases lock.
 *
 * @param lock Pointer to lock structure.
 *
 * @return ESP_OK on success, otherwise \see esp_err_t
 */
esp_err_t esp_apptrace_lock_give(esp_apptrace_lock_t *lock);

/** Ring buffer control structure.
 *
 * @note For purposes of application tracing module if there is no enough space for user data and write pointer can be wrapped
 *       current ring buffer size can be temporarily shrinked in order to provide buffer with requested size.
 */
typedef struct {
    uint8_t *data;      ///< pointer to data storage
    volatile uint32_t size;      ///< size of data storage
    volatile uint32_t cur_size;  ///< current size of data storage
    volatile uint32_t rd;        ///< read pointer
    volatile uint32_t wr;        ///< write pointer
} esp_apptrace_rb_t;

/**
 * @brief Initializes ring buffer control  structure.
 *
 * @param rb   Pointer to ring buffer structure to be initialized.
 * @param data Pointer to buffer to be used as ring buffer's data storage.
 * @param size Size of buffer to be used as ring buffer's data storage.
 */
static inline void esp_apptrace_rb_init(esp_apptrace_rb_t *rb, uint8_t *data, uint32_t size)
{
    rb->data = data;
    rb->size = rb->cur_size = size;
    rb->rd = 0;
    rb->wr = 0;
}

/**
 * @brief Allocates memory chunk in ring buffer.
 *
 * @param rb   Pointer to ring buffer structure.
 * @param size Size of the memory to allocate.
 *
 * @return Pointer to the allocated memory or NULL in case of failure.
 */
uint8_t *esp_apptrace_rb_produce(esp_apptrace_rb_t *rb, uint32_t size);

/**
 * @brief Consumes memory chunk in ring buffer.
 *
 * @param rb   Pointer to ring buffer structure.
 * @param size Size of the memory to consume.
 *
 * @return Pointer to consumed memory chunk or NULL in case of failure.
 */
uint8_t *esp_apptrace_rb_consume(esp_apptrace_rb_t *rb, uint32_t size);

/**
 * @brief Gets size of memory which can consumed with single call to esp_apptrace_rb_consume().
 *
 * @param rb Pointer to ring buffer structure.
 *
 * @return Size of memory which can consumed.
 *
 * @note Due to read pointer wrapping returned size can be less then the total size of available data.
 */
uint32_t esp_apptrace_rb_read_size_get(esp_apptrace_rb_t *rb);

/**
 * @brief Gets size of memory which can produced with single call to esp_apptrace_rb_produce().
 *
 * @param rb Pointer to ring buffer structure.
 *
 * @return Size of memory which can produced.
 *
 * @note Due to write pointer wrapping returned size can be less then the total size of available data.
 */
uint32_t esp_apptrace_rb_write_size_get(esp_apptrace_rb_t *rb);

int esp_apptrace_log_lock(void);
void esp_apptrace_log_unlock(void);

#define ESP_APPTRACE_LOG( format, ... )   \
    do { \
        esp_apptrace_log_lock(); \
        esp_rom_printf(format, ##__VA_ARGS__); \
        esp_apptrace_log_unlock(); \
    } while(0)

#define ESP_APPTRACE_LOG_LEV( _L_, level, format, ... )   \
    do { \
        if (LOG_LOCAL_LEVEL >= level) { \
            ESP_APPTRACE_LOG(LOG_FORMAT(_L_, format), esp_log_early_timestamp(), TAG, ##__VA_ARGS__); \
        } \
    } while(0)

#define ESP_APPTRACE_LOGE( format, ... )  ESP_APPTRACE_LOG_LEV(E, ESP_LOG_ERROR, format, ##__VA_ARGS__)
#define ESP_APPTRACE_LOGW( format, ... )  ESP_APPTRACE_LOG_LEV(W, ESP_LOG_WARN, format, ##__VA_ARGS__)
#define ESP_APPTRACE_LOGI( format, ... )  ESP_APPTRACE_LOG_LEV(I, ESP_LOG_INFO, format, ##__VA_ARGS__)
#define ESP_APPTRACE_LOGD( format, ... )  ESP_APPTRACE_LOG_LEV(D, ESP_LOG_DEBUG, format, ##__VA_ARGS__)
#define ESP_APPTRACE_LOGV( format, ... )  ESP_APPTRACE_LOG_LEV(V, ESP_LOG_VERBOSE, format, ##__VA_ARGS__)
#define ESP_APPTRACE_LOGO( format, ... )  ESP_APPTRACE_LOG_LEV(E, ESP_LOG_NONE, format, ##__VA_ARGS__)

#ifdef __cplusplus
}
#endif

#endif //ESP_APP_TRACE_UTIL_H_


text:
<?php

use yii\db\Migration;

class m161126_184646_create_events extends Migration
{
    public function safeUp()
    {
        $tableOptions = null;

        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('event', [
            'id' => $this->primaryKey(),
            'type' => $this->smallInteger()->notNull(),
            'trig_date' => $this->string(),
            'trig_time' => $this->string(),
            'trig_time_wdays' => $this->string(),
            'trig_item_id' => $this->integer(),
            'trig_item_value' => $this->string(),
            'task_id' => $this->integer(),
            'name' => $this->string()->notNull(),
        ], $tableOptions);
    }

    public function safeDown()
    {
        $this->dropTable('event');
    }
}


text:
package org.innovateuk.ifs.commons.security.evaluator;

import java.util.LinkedHashMap;

/**
 * An alias for a map that maps protected classes (e.g. ApplicationResource) to the permissions methods that
 * protect them.  Specifically, it maps them to a {@link PermissionsToPermissionsMethods} which holds
 * a list of protected actions (e.g. "READ", "WRITE") and the permission methods that support each action.
 * Therefore this map holds the means by which to look up, for example, all permission methods that
 * protect an ApplicationResource against a "READ" action.
 */
public class PermissionedObjectClassToPermissionsToPermissionsMethods
        extends LinkedHashMap<Class<?>, PermissionsToPermissionsMethods> {
}


text:
package gaia3d.api;

import gaia3d.domain.datalibrary.DataLibrary;
import gaia3d.domain.datalibrary.DataLibraryDto;
import gaia3d.service.DataLibraryService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.modelmapper.ModelMapper;
import org.springframework.hateoas.CollectionModel;
import org.springframework.hateoas.EntityModel;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static org.springframework.hateoas.server.mvc.WebMvcLinkBuilder.linkTo;

@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping(value = "/api/data-libraries", produces = MediaTypes.HAL_JSON_VALUE)
public class DataLibraryApiController {

    private final DataLibraryService dataLibraryService;
    private final ModelMapper modelMapper;

    /**
     * 데이터 라이브러리 목록 조회
     *
     * @return
     */
    @GetMapping
    public ResponseEntity<CollectionModel<EntityModel<DataLibraryDto>>> getDataLibraries(@RequestParam(defaultValue = "0") Integer dataLibraryGroupId) {
        List<DataLibrary> dataLibraryList = dataLibraryService.getListDataLibrary(DataLibrary.builder().dataLibraryGroupId(dataLibraryGroupId).build());
        List<EntityModel<DataLibraryDto>> dataLibraryDtoList = dataLibraryList.stream()
                .map(f -> EntityModel.of(modelMapper.map(f, DataLibraryDto.class))
                        .add(linkTo(DataLibraryApiController.class).slash(f.getDataLibraryId()).withSelfRel()))
                .collect(Collectors.toList());

        CollectionModel<EntityModel<DataLibraryDto>> model = CollectionModel.of(dataLibraryDtoList);

        model.add(linkTo(DataLibraryApiController.class).withSelfRel());
        model.add(Link.of("/docs/index.html#resources-data-library-list").withRel("profile"));

        return ResponseEntity.ok(model);
    }

    /**
     * 데이터 라이브러리 한건 조회
     *
     * @param id 데이터 라이브러리 아이디
     * @return
     */
    @GetMapping("/{id}")
    public ResponseEntity<EntityModel<DataLibraryDto>> getDataLibraryById(@PathVariable("id") Long id) {
        DataLibraryDto dto = modelMapper.map(dataLibraryService.getDataLibrary(DataLibrary.builder().dataLibraryId(id).build()), DataLibraryDto.class);
        EntityModel<DataLibraryDto> dataLibrary = EntityModel.of(dto);
        dataLibrary.add(linkTo(DataLibraryApiController.class).slash(id).withSelfRel());
        dataLibrary.add(Link.of("/docs/index.html#resources-data-library-get").withRel("profile"));

        return ResponseEntity.ok(dataLibrary);
    }
}


text:
using namespace std;

class rkWindow : public Fl_Double_Window
{
public:
	rkWindow(int X, int Y, int W, int H, const char *l=0);
	rkWindow(int W, int H, const char *l=0);

	static void addObject(IDeactivate *d) { objs.push_back(d); }
	static vector<IDeactivate *> objs;

	int handle(int evt);

	void manual_resize(int w, int h);
	void show();
	void hide();

	virtual void capture();

protected:
	unsigned int createdW, createdH;
	int createdX, createdY;
	bool first;
};

#endif


text:
// Copyright (c) 2016-2018, Siddharth Maddali
// All rights reserved.
//
// 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 Carnegie Mellon University 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.
/*
 *
 * HierarchicalSmooth.cpp -- implementation of the routines declared in HierarchicalSmooth.h
 *
 */

#include "HierarchicalSmooth.h"

//============================================================================================

SpMat HSmoothMain::Laplacian2D( int N, std::string type ) {

	std::vector< T > tripletList;
	tripletList.reserve( 3*N ); // approx. number of nonzero elements
	for( int i = 0; i < N; i++ ) {
		tripletList.push_back( T( i, i, -1.0 ) );
		if( i != N-1 )
			tripletList.push_back( T( i, i+1, 1.0 ) );
	}
	SpMat temp( N, N );
	temp.setFromTriplets( tripletList.begin(), tripletList.end() );
	SpMat L = SpMat( temp.transpose() ) * temp;
	if( type=="serial" ){
		L.coeffRef( N-1, N-1 ) = 1.0;
	}
	else if( type=="cyclic" ) {
		L.coeffRef( 0, 0 ) = 2.0;
		L.coeffRef( 0, N-1 ) = L.coeffRef( N-1, 0 ) = -1.0;
	}
	else
		std::cerr << "HSmoothMain::Laplacian2D: Unrecognized type. " << std::endl;

	L.makeCompressed();
	return L;
}

//============================================================================================

std::tuple< SpMat, std::vector< int> > HSmoothMain::GraphLaplacian( trimesh& tri ) {

	std::vector< int > nUnique;
	for( int i = 0; i < tri.rows(); i++ )
		for( int j = 0; j < tri.cols(); j++ )
			nUnique.push_back( tri( i, j ) );
	std::sort( nUnique.begin(), nUnique.end() );
	nUnique.erase( std::unique( nUnique.begin(), nUnique.end() ), nUnique.end() );

	std::vector< T > tripletList;
	tripletList.reserve( nUnique.size() + tri.rows()*tri.cols()*2 );

	std::vector< double > fDiagCount( nUnique.size(), 0.0 );

	trimesh nSubTri = HSmoothBase::ismember( tri, nUnique );

	DictBase< int >::EdgeDict MyDict;
	for( int i = 0; i < nSubTri.rows(); i++ ) {
		for( int j = 0; j < 3; j++ ) {
			int l = ( j + 3 ) % 3;
			int m = ( j + 4 ) % 3;
			int this_row = nSubTri(i,l);
			int this_col = nSubTri(i,m);
			EdgePair EP = std::make_pair( std::min( this_row, this_col ), std::max( this_row, this_col ) );
			DictBase< int >::EdgeDict::const_iterator got = MyDict.find( EP );
			if( got == MyDict.end() ) {				// not found yet...
				MyDict.insert( { EP, i } );			// i.e. the edge, and one of the triangles it belongs to.
				tripletList.push_back( T( this_row, this_col, -1.0 ) );
				tripletList.push_back( T( this_col, this_row, -1.0 ) );
				fDiagCount[ this_row ] += 1.0;
				fDiagCount[ this_col ] += 1.0;
			}

		}
	}

	for( int i = 0; i < fDiagCount.size(); i++ )
		tripletList.push_back( T( i, i, fDiagCount[i] ) );

	SpMat MLap( nUnique.size(), nUnique.size() );
	MLap.setFromTriplets( tripletList.begin(), tripletList.end() );
	MLap.makeCompressed();
	return std::make_tuple( MLap, nUnique );
}

//============================================================================================

meshnode HSmoothMain::Smooth( meshnode& NodesIn, std::string type, double fThresh, int nIter ) {
	SpMat L = Laplacian2D( NodesIn.cols(), type );
	std::vector< int > vidx;
	if( type=="serial" )
		vidx = std::vector< int >{ (int)0, (int)(L.cols()-1) };
	else
		vidx = std::vector< int >{};
	matindex nFixed = HSmoothBase::getindex( vidx );
	return Smooth( NodesIn, nFixed, L, fThresh, nIter );
}

//============================================================================================

meshnode HSmoothMain::Smooth( meshnode& NodesIn, matindex& nFixed, SpMat& GL, double fThresh, int nIter ) {
	matindex nMobile = HSmoothBase::getcomplement( nFixed, GL.cols() );
	if( nMobile.size() == 0 )
		return NodesIn;

	SpMat Data = NodesIn.transpose().sparseView();

	SpMat GLRed, fConst, D, A, AyIn, yMobile, fSmallEye, LTL, LTK, yOut;

	std::tuple< SpMat, SpMat > dbvp = GetDirichletBVP( GL, Data, nFixed, nMobile );
	GLRed = std::get<0>( dbvp );
	fConst = std::get<1>( dbvp );

	std::tuple< SpMat, SpMat > pieces = AnalyzeLaplacian( GL );
	D = std::get<0>( pieces );
	A = std::get<1>( pieces );

	AyIn = A * Data;
	Eigen::MatrixXd mtemp = Eigen::MatrixXd::Zero( nMobile.size(), nMobile.size() );
	mtemp.setIdentity();
	fSmallEye = mtemp.sparseView();
	fSmallEye.makeCompressed();
	igl::slice( Data, nMobile, 1, yMobile );
	LTL = SpMat( GLRed.transpose() * GLRed );
	LTK = SpMat( GLRed.transpose() * fConst );	// casting as SpMat to make column-major
	yOut = Data;

	Smoother smth;

	double fEps = 0.5;
	double fStep = fEps / 2.0;
	int nCount = 1;

	double fobj1, fobj2, fslope;
	fobj1 = GetObjFn( smth, fEps, fSmallEye, LTL, LTK, Data, nMobile, yMobile, D, AyIn, yOut ); 	// only the last parameter is actually modified
	fobj2 = GetObjFn( smth, fEps+fThresh, fSmallEye, LTL, LTK, Data, nMobile, yMobile, D, AyIn, yOut );
	fslope = ( fobj2 - fobj1 ) / fThresh;

	while( fabs( fslope ) < fThresh && nCount < nIter ) {
		if( fStep > 0.0 )
			fEps -= fStep;
		else
			fEps += fStep;

		fEps /= 2.0;
		fobj1 = GetObjFn( smth, fEps, fSmallEye, LTL, LTK, Data, nMobile, yMobile, D, AyIn, yOut ); 	// only the last parameter is actually modified
		fobj2 = GetObjFn( smth, fEps+fThresh, fSmallEye, LTL, LTK, Data, nMobile, yMobile, D, AyIn, yOut );
		fslope = ( fobj2 - fobj1 ) / fThresh;
		nCount++;
	}

	return Eigen::MatrixXd( yOut.transpose() );

}

//============================================================================================

std::tuple< SpMat, SpMat > HSmoothMain::GetDirichletBVP( SpMat& GL, SpMat& yIn, matindex& nFixed, matindex& nMobile ) {

	matindex nAll = HSmoothBase::matunion( nFixed, nMobile );
	std::vector< int > v;
	for( int i = 0; i < yIn.cols(); i++ ) v.push_back( i );
	matindex dims = HSmoothBase::getindex( v );

//	SpMat GLRed, sm1, sm2, sm3, fConst;
	SpMat	GLRed( nMobile.size(), nMobile.size() ),
			sm1( nAll.size(), nFixed.size() ),
			sm2( nFixed.size(), dims.size() ),
			sm3( nAll.size(), dims.size() ),
			fConst( nMobile.size(), dims.size() );

	igl::slice( GL, nMobile, nMobile, GLRed );		// thank goodness for igl::slice!
	igl::slice( GL, nAll, nFixed, sm1 );
	igl::slice( yIn, nFixed, dims, sm2 );
	sm3 = sm1*sm2;
	igl::slice( sm3, nMobile, dims, fConst );

	return std::make_tuple( GLRed, fConst );
}

//============================================================================================

std::tuple< SpMat, SpMat > HSmoothMain::AnalyzeLaplacian( SpMat& GL ) {	// NOTE: GL should be column-major

	SpMat D( GL.rows(), GL.cols() ), A( GL.rows(), GL.cols() );
	std::vector< T > DT, AT;

	for( int k = 0; k < GL.outerSize(); ++k ) {
		for( SpMat::InnerIterator it( GL, k ); it; ++it ) {
			if( it.value() < -0.5 )
				AT.push_back( T( it.row(), it.col(), it.value() ) );
			else if( it.value() > 0.5 )
				DT.push_back( T( it.row(), it.col(), it.value() ) );
		}
	}
	D.setFromTriplets( DT.begin(), DT.end() );
	A.setFromTriplets( AT.begin(), AT.end() );

	D.makeCompressed();
	A.makeCompressed();

	return std::make_tuple( D, A );

}

//============================================================================================

double HSmoothMain::GetObjFn( Smoother& smth, double feps,
		SpMat& fSmallEye, SpMat& LTL, SpMat& LTK,
		SpMat& Data, matindex& nMobile, SpMat& yMobile,
		SpMat& D, SpMat& AyIn, SpMat& yOut ) {

	SpMat ySmooth;

	SpMat A = ( 1.0 - feps )*fSmallEye	+ feps*LTL;
	SpMat b = ( 1.0 - feps )*yMobile	- feps*LTK;

	smth.compute( A );			// smth in general changes with each function call
	ySmooth = smth.solve( b );

	HSmoothBase::merge( ySmooth, yOut, nMobile );

	Eigen::ArrayXXd yDeltaD = Eigen::MatrixXd( D*yOut + AyIn ).array();

	return ( yDeltaD * yDeltaD ).sum();	// more efficient to calculate trace this way

}


text:
/**
 * @description Implement the rich layout for the module admin pages
 * @author Cláudio Esperança, Diogo Serra
 * @version 1.0
 */
var $j = jQuery.noConflict();

$j(function(){

    // Localize and set the common options for the calendars
    var calendarOptions = {
        closeText: vpmAdminL10n.closeText,
        currentText: vpmAdminL10n.currentText,
        dateFormat: vpmAdminL10n.dateFormat,
        dayNames: [
            vpmAdminL10n.dayNamesSunday,
            vpmAdminL10n.dayNamesMonday,
            vpmAdminL10n.dayNamesTuesday,
            vpmAdminL10n.dayNamesWednesday,
            vpmAdminL10n.dayNamesThursday,
            vpmAdminL10n.dayNamesFriday,
            vpmAdminL10n.dayNamesSaturday
        ],
        dayNamesMin: [
            vpmAdminL10n.dayNamesMinSu,
            vpmAdminL10n.dayNamesMinMo,
            vpmAdminL10n.dayNamesMinTu,
            vpmAdminL10n.dayNamesMinWe,
            vpmAdminL10n.dayNamesMinTh,
            vpmAdminL10n.dayNamesMinFr,
            vpmAdminL10n.dayNamesMinSa
        ],
        dayNamesShort: [
            vpmAdminL10n.dayNamesShortSun,
            vpmAdminL10n.dayNamesShortMon,
            vpmAdminL10n.dayNamesShortTue,
            vpmAdminL10n.dayNamesShortWed,
            vpmAdminL10n.dayNamesShortThu,
            vpmAdminL10n.dayNamesShortFri,
            vpmAdminL10n.dayNamesShortSat
        ],
        monthNames: [
            vpmAdminL10n.monthNamesJanuary,
            vpmAdminL10n.monthNamesFebruary,
            vpmAdminL10n.monthNamesMarch,
            vpmAdminL10n.monthNamesApril,
            vpmAdminL10n.monthNamesMay,
            vpmAdminL10n.monthNamesJune,
            vpmAdminL10n.monthNamesJuly,
            vpmAdminL10n.monthNamesAugust,
            vpmAdminL10n.monthNamesSeptember,
            vpmAdminL10n.monthNamesOctober,
            vpmAdminL10n.monthNamesNovember,
            vpmAdminL10n.monthNamesDecember
        ],
        monthNamesShort: [
            vpmAdminL10n.monthNamesShortJan,
            vpmAdminL10n.monthNamesShortFeb,
            vpmAdminL10n.monthNamesShortMar,
            vpmAdminL10n.monthNamesShortApr,
            vpmAdminL10n.monthNamesShortMay,
            vpmAdminL10n.monthNamesShortJun,
            vpmAdminL10n.monthNamesShortJul,
            vpmAdminL10n.monthNamesShortAug,
            vpmAdminL10n.monthNamesShortSep,
            vpmAdminL10n.monthNamesShortOct,
            vpmAdminL10n.monthNamesShortNov,
            vpmAdminL10n.monthNamesShortDec
        ],
        nextText: vpmAdminL10n.nextText,
        prevText: vpmAdminL10n.prevText,
        weekHeader: vpmAdminL10n.weekHeader,
        altFormat: "yy-m-d",
        autoSize: true,
        changeMonth: true,
        changeYear: true
    },
    timeDefaults = {
        'min': 0,
        'showOn': 'none',
        'width': 24,
        'mouseWheel': true,
        'step': 1,
        'largeStep': 1
    },
    startDate = null,
    endDate = null;

    // Hide the hidden elements
    $j(".start-hidden").hide();

    // Container function to show and style the fieldsets accordingly
    function showContainer(innerContainer, outerContainer, show){
        if(show){
            $j(outerContainer).addClass("vpm-visible");
            $j(innerContainer).show();
        }else{
            $j(innerContainer).hide();
            $j(outerContainer).removeClass("vpm-visible");
        }
    };

    $j("#vpm-enable-startdate").click(function(){
        showContainer("#vpm-startdate-container", "#vpm-enable-startdate-container", $j(this).is(":checked"));

        // Reset the minDate for the other calendar
        if(!$j(this).is(":checked")){
            $j("#vpm-enddate").datepicker("option", "minDate", null);
        }
    });
    $j("#vpm-enable-enddate").click(function(){
        showContainer("#vpm-enddate-container", "#vpm-enable-enddate-container", $j(this).is(":checked"));

        // Reset the minDate for the other calendar
        if(!$j(this).is(":checked")){
            $j("#vpm-startdate").datepicker("option", "maxDate", null);
        }
    });

    // Attach the date picker components and set their dates based on the timestamp values
    if($j("#vpm-hidden-startdate").val()){
        startDate = $j.datepicker.parseDate(calendarOptions.altFormat, $j("#vpm-hidden-startdate").val()) || null;
    }
    if($j("#vpm-hidden-enddate").val()){
        endDate = $j.datepicker.parseDate(calendarOptions.altFormat, $j("#vpm-hidden-enddate").val()) || null;
    }

    $j("#vpm-startdate").datepicker($j.extend(true, {}, calendarOptions, {
        defaultDate: "+1w",
        altField: "#vpm-hidden-startdate",
        maxDate: $j("#vpm-enable-enddate").is(":checked")?endDate:null,
        onSelect: function( selectedDate ) {
            if($j("#vpm-enable-enddate").is(":checked")){
                var instance = $j(this).data( "datepicker" ),
                date = $j.datepicker.parseDate(instance.settings.dateFormat || $j.datepicker._defaults.dateFormat, selectedDate, instance.settings );

                $j("#vpm-enddate").datepicker( "option", "minDate", date );
            }else{
                $j("#vpm-enddate").datepicker( "option", "minDate", null );
            }
        }
    })).datepicker("setDate", startDate);

    $j("#vpm-enddate").datepicker($j.extend(true, {}, calendarOptions, {
        defaultDate: "+2w",
        altField: "#vpm-hidden-enddate",
        minDate: $j("#vpm-enable-startdate").is(":checked")?startDate:null,
        onSelect: function( selectedDate ) {
            if($j("#vpm-enable-startdate").is(":checked")){
                var instance = $j(this).data( "datepicker" ),
                    date = $j.datepicker.parseDate(instance.settings.dateFormat || $j.datepicker._defaults.dateFormat, selectedDate, instance.settings );
                $j("#vpm-startdate").datepicker( "option", "maxDate", date );
            }else{
                $j("#vpm-startdate").datepicker( "option", "minDate", null );
            }
        }
    })).datepicker("setDate", endDate);

    // Set the initial visibility of the fieldsets
    showContainer("#vpm-startdate-container", "#vpm-enable-startdate-container", $j("#vpm-enable-startdate").is(":checked"));
    showContainer("#vpm-enddate-container", "#vpm-enable-enddate-container", $j("#vpm-enable-enddate").is(":checked"));

    // Since the link exists, we need to handle the case when the user clicks on it...
    $j('#vpm_projectFile_delete:checkbox').click(function(evt) {

            if($j(this).attr('checked')){
                // Hide the view link
                $j('a#vpm_projectFile_view').hide();
            }else{
                // Show the view link
                $j('a#vpm_projectFile_view').show();
            }

    });

    $j("#vpm_projectFile_download").click(function(){
        var old = parseInt($j('#vpm-downloadCounter').html(),10);
        $j('#vpm-downloadCounter').html(old+1);
        return true;
    });

});


text:
<?php

namespace App\Shell;

use App\Model\Entity\Device;
use App\Model\Entity\DeviceData;
use App\Model\Entity\DeviceSoftware;
use Cake\Console\Shell;
use Cake\I18n\Time;
use SNMP;

/**
 * Query shell command.
 *
 * @property App\Model\Table\DevicesTable $Devices Devices Model
 * @property App\Model\Table\DeviceSoftwareTable $DeviceSoftware Devices Model
 * @property Task\SnmpTask $Snmp Snmp Task
 */
class QueryShell extends Shell
{
    /**
     * Lista de tasks para serem inicializadas.
     *
     * @var array
     */
    public $tasks = ['Snmp'];

    /**
     * Inicializa o shell, carregando os models necessários.
     */
    public function initialize()
    {
        parent::initialize();
        $this->loadModel('Devices');
        $this->loadModel('DeviceSoftware');
    }

    /**
     * main() method.
     *
     * @return bool|int Success or error code.
     */
    public function main()
    {
        $devices = $this->Devices->findUpdatePending();

        foreach ($devices as $device) {
            $this->updateDevice($device);
        }

        return true;
    }

    /**
     * Updates a device by issuing SNMP GET requests for all informations
     * that this software handles.
     *
     * @param Device $device Device to be updated.
     */
    private function updateDevice(Device $device)
    {
        $this->Snmp->open(SNMP::VERSION_2C, $device->ip_address, $device->snmp_community);

        // Remove old list of softwares of this device and get a new one
        $this->DeviceSoftware->deleteAll(['device_id' => $device->id]);
        $device->device_softwares = $this->queryDeviceSoftware();

        // Get other informations from the device
        $device->appendDeviceData($this->queryDeviceData());

        // Save them all
        $device->last_updated = Time::now();
        $this->Devices->save($device);

        $this->Snmp->close();
    }

    /**
     * Get scalar information from one device.
     *
     * @return DeviceData Object with latest information for the device.
     */
    private function queryDeviceData()
    {
        $data = $this->Snmp->getMany([
            'description'    => 'SNMPv2-MIB::sysDescr.0',
            'uptime'         => 'HOST-RESOURCES-MIB::hrSystemUptime.0',
            'total_ram'      => 'UCD-SNMP-MIB::memTotalReal.0',
            'available_ram'  => 'UCD-SNMP-MIB::memAvailReal.0',
            'total_disk'     => 'UCD-SNMP-MIB::dskTotal.1',
            'available_disk' => 'UCD-SNMP-MIB::dskAvail.1',
            'used_disk'      => 'UCD-SNMP-MIB::dskUsed.1'
        ]);

        $deviceData = new DeviceData($data);
        $deviceData->used_ram = $deviceData->total_ram - $deviceData->available_ram;
        $deviceData->updated = new \DateTime();

        return $deviceData;
    }

    /**
     * Get table of softwares installed on device.
     *
     * @return DeviceSoftware[] Array of objects with table of installed software.
     */
    private function queryDeviceSoftware()
    {
        $list = $this->Snmp->getList('HOST-RESOURCES-MIB::hrSWInstalledName');
        $softwares = [];

        foreach ($list as $name) {
            $software = new DeviceSoftware();
            $software->name = $name;
            $softwares[] = $software;
        }

        return $softwares;
    }
}


text:
package com.palantir.giraffe.host;

import java.io.IOException;

/**
 * Contains information required to authenticate with a host or service.
 *
 * @author bkeyes
 *
 * @param <A> the type of {@link Authenticator} that accepts this credential
 */
public abstract class Credential<A extends Authenticator> {

    private final Class<A> authenticatorType;

    protected Credential(Class<A> authenticatorType) {
        this.authenticatorType = authenticatorType;
    }

    /**
     * Returns the type of {@link Authenticator} accepted by this credential.
     */
    public final Class<A> getAuthenticatorType() {
        return authenticatorType;
    }

    /**
     * Authenticates the connection managed by the given {@link Authenticator}
     * using this credential.
     * <p>
     * This method participates in the visitor pattern with methods defined by
     * {@code Authenticator} implementations.
     *
     * @param authenticator the {@code Authenticator} for the connection
     *
     * @throws AuthenticationException if authentication fails
     * @throws IOException if an I/O error occurs while authenticating the
     *         connection
     */
    public abstract void authenticate(A authenticator) throws IOException;
}


text:
import math
from django import template
from .. import *

register = template.Library()

@register.inclusion_tag('googlesearch/pagination.html', takes_context=True)
def show_pagination(context, pages_to_show=10):

    """ Find the last possible page """
    last_page = math.ceil(context['total_results'] / GOOGLE_SEARCH_RESULTS_PER_PAGE)

    """ The last page will be either the
        user-specified maximum page, or the
        last page that was returned, whichever
        was lower """
    last_page = min([GOOGLE_SEARCH_MAX_PAGES, int(last_page)])

    prev_page = context['current_page'] - 1

    next_page = context['current_page'] + 1

    context.update({
        'pages': range(1, last_page + 1),
        'prev_page': prev_page if context['current_page'] - 1 > 0 else None,
        'next_page': next_page if next_page < last_page else None,
    })

    return context


text:
package com.it.utility;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;

import java.util.ArrayList;

public class EmailFetcher {

	public static String getName(Context context) {
		Cursor CR = null;
		CR = getOwner(context);
		String id = "", name = "";
		while (CR.moveToNext()) {
			name = CR.getString(CR
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
		}

		return name;
	}

	public static String getEmailId(Context context) {

		Cursor CR = null;
		CR = getOwner(context);
		String id = "", email = "";
		while (CR.moveToNext()) {
			id = CR.getString(CR
					.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID));
			email = CR
					.getString(CR
							.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
		}
		return email;
	}

	static Cursor getOwner(Context context) {

		String accountName = null;
		Cursor emailCur = null;
		AccountManager accountManager = AccountManager.get(context);
		Account[] accounts = accountManager.getAccountsByType("com.google");
		if (accounts.length != 0 && accounts[0].name != null) {
			accountName = accounts[0].name;
			String where = ContactsContract.CommonDataKinds.Email.DATA + " = ?";
			ArrayList<String> what = new ArrayList<String>();
			what.add(accountName);
			Log.v("Got account", "Account " + accountName);
			for (int i = 1; i < accounts.length; i++) {
				where += " or " + ContactsContract.CommonDataKinds.Email.DATA
						+ " = ?";
				what.add(accounts[i].name);
				Log.v("Got account", "Account " + accounts[i].name);
			}
			String[] whatarr = (String[]) what.toArray(new String[what.size()]);
			ContentResolver cr = context.getContentResolver();
			emailCur = cr.query(
					ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
					where, whatarr, null);

			/*
			 * if (id != null) {
			 *
			 * // get the phone number Cursor pCur = cr.query(
			 * ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
			 * ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new
			 * String[]{id}, null); while (pCur.moveToNext()) { phone = pCur
			 * .getString(pCur
			 * .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
			 * Log.v("Got contacts", "phone" + phone); } pCur.close(); }
			 */
		}
		return emailCur;
	}

}


text:
 #define GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS 0
#endif

#if GPB_USE_PROTOBUF_FRAMEWORK_IMPORTS
 #import <Protobuf/GPBProtocolBuffers.h>
#else
 #import "GPBProtocolBuffers.h"
#endif

#if GOOGLE_PROTOBUF_OBJC_GEN_VERSION != 30001
#error This file was generated by a different version of protoc which is incompatible with your Protocol Buffer library sources.
#endif

// @@protoc_insertion_point(imports)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"

CF_EXTERN_C_BEGIN

NS_ASSUME_NONNULL_BEGIN

#pragma mark - Enum InventoryUpgradeType

typedef GPB_ENUM(InventoryUpgradeType) {
  /// Value used if any message's field encounters a value that is not defined
  /// by this enum. The message will also have C functions to get/set the rawValue
  /// of the field.
  InventoryUpgradeType_GPBUnrecognizedEnumeratorValue = kGPBUnrecognizedEnumeratorValue,
  InventoryUpgradeType_UpgradeUnset = 0,
  InventoryUpgradeType_IncreaseItemStorage = 1,
  InventoryUpgradeType_IncreasePokemonStorage = 2,
};

GPBEnumDescriptor *InventoryUpgradeType_EnumDescriptor(void);

/// Checks to see if the given value is defined by the enum or was not known at
/// the time this source was generated.
BOOL InventoryUpgradeType_IsValidValue(int32_t value);

#pragma mark - InventoryUpgradeTypeRoot

/// Exposes the extension registry for this file.
///
/// The base class provides:
/// @code
///   + (GPBExtensionRegistry *)extensionRegistry;
/// @endcode
/// which is a @c GPBExtensionRegistry that includes all the extensions defined by
/// this file and all files that it depends on.
@interface InventoryUpgradeTypeRoot : GPBRootObject
@end

NS_ASSUME_NONNULL_END

CF_EXTERN_C_END

#pragma clang diagnostic pop

// @@protoc_insertion_point(global_scope)


text:
package org.apache.nifi.jms.processors;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import javax.jms.Destination;
import javax.jms.Message;

import org.apache.nifi.annotation.behavior.InputRequirement;
import org.apache.nifi.annotation.behavior.InputRequirement.Requirement;
import org.apache.nifi.annotation.documentation.CapabilityDescription;
import org.apache.nifi.annotation.documentation.SeeAlso;
import org.apache.nifi.annotation.documentation.Tags;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.jms.cf.JMSConnectionFactoryProvider;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.Processor;
import org.apache.nifi.processor.Relationship;
import org.apache.nifi.processor.exception.ProcessException;
import org.apache.nifi.stream.io.StreamUtils;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.support.JmsHeaders;

/**
 * An implementation of JMS Message publishing {@link Processor} which upon each
 * invocation of {@link #onTrigger(ProcessContext, ProcessSession)} method will
 * construct a {@link Message} from the contents of the {@link FlowFile} sending
 * it to the {@link Destination} identified by the
 * {@link AbstractJMSProcessor#DESTINATION} property while transferring the
 * incoming {@link FlowFile} to 'success' {@link Relationship}. If message can
 * not be constructed and/or sent the incoming {@link FlowFile} will be
 * transitioned to 'failure' {@link Relationship}
 */
@Tags({ "jms", "put", "message", "send", "publish" })
@InputRequirement(Requirement.INPUT_REQUIRED)
@CapabilityDescription("Creates a JMS Message from the contents of a FlowFile and sends it to a "
        + "JMS Destination (queue or topic) as JMS BytesMessage. FlowFile attributes will be added as JMS headers and/or properties to the outgoing JMS message.")
@SeeAlso(value = { ConsumeJMS.class, JMSConnectionFactoryProvider.class })
public class PublishJMS extends AbstractJMSProcessor<JMSPublisher> {

    public static final Relationship REL_SUCCESS = new Relationship.Builder()
            .name("success")
            .description("All FlowFiles that are sent to the JMS destination are routed to this relationship")
            .build();
    public static final Relationship REL_FAILURE = new Relationship.Builder()
            .name("failure")
            .description("All FlowFiles that cannot be sent to JMS destination are routed to this relationship")
            .build();

    private final static Set<Relationship> relationships;

    /*
     * Will ensure that the list of property descriptors is build only once.
     * Will also create a Set of relationships
     */
    static {
        Set<Relationship> _relationships = new HashSet<>();
        _relationships.add(REL_SUCCESS);
        _relationships.add(REL_FAILURE);
        relationships = Collections.unmodifiableSet(_relationships);
    }

    /**
     * Will construct JMS {@link Message} by extracting its body from the
     * incoming {@link FlowFile}. {@link FlowFile} attributes that represent
     * standard JMS headers will be extracted from the {@link FlowFile} and set
     * as JMS headers on the newly constructed message. For the list of
     * available message headers please see {@link JmsHeaders}.

     *

     * Upon success the incoming {@link FlowFile} is transferred to the'success'
     * {@link Relationship} and upon failure FlowFile is penalized and
     * transferred to the 'failure' {@link Relationship}
     */
    @Override
    protected void rendezvousWithJms(ProcessContext context, ProcessSession processSession, JMSPublisher publisher) throws ProcessException {
        FlowFile flowFile = processSession.get();
        if (flowFile != null) {
            try {
                String destinationName = context.getProperty(DESTINATION).evaluateAttributeExpressions(flowFile).getValue();
                publisher.publish(destinationName, this.extractMessageBody(flowFile, processSession), flowFile.getAttributes());
                processSession.transfer(flowFile, REL_SUCCESS);
                processSession.getProvenanceReporter().send(flowFile, context.getProperty(DESTINATION).evaluateAttributeExpressions().getValue());
            } catch (Exception e) {
                processSession.transfer(flowFile, REL_FAILURE);
                this.getLogger().error("Failed while sending message to JMS via " + publisher, e);
                context.yield();
            }
        }
    }

    /**
     *
     */
    @Override
    public Set<Relationship> getRelationships() {
        return relationships;
    }

    /**
     * Will create an instance of {@link JMSPublisher}
     */
    @Override
    protected JMSPublisher finishBuildingJmsWorker(CachingConnectionFactory connectionFactory, JmsTemplate jmsTemplate, ProcessContext processContext) {
        return new JMSPublisher(connectionFactory, jmsTemplate, this.getLogger());
    }

    /**
     * Extracts contents of the {@link FlowFile} as byte array.
     */
    private byte[] extractMessageBody(FlowFile flowFile, ProcessSession session) {
        final byte[] messageContent = new byte[(int) flowFile.getSize()];
        session.read(flowFile, in -> StreamUtils.fillBuffer(in, messageContent, true));
        return messageContent;
    }
}


text:
BuildrPlus::FeatureManager.feature(:config) do |f|
  f.enhance(:Config) do
    attr_writer :application_config_location

    def application_config_location
      base_directory = File.dirname(Buildr.application.buildfile.to_s)
      "#{base_directory}/config/application.yml"
    end

    def application_config_example_location
      application_config_location.gsub(/\.yml$/, '.example.yml')
    end

    def application_config
      @application_config ||= load_application_config
    end

    attr_writer :environment

    def environment
      @environment || 'development'
    end

    def environment_config
      raise "Attempting to configuration for #{self.environment} environment which is not present." unless self.application_config.environment_by_key?(self.environment)
      self.application_config.environment_by_key(self.environment)
    end

    def domain_environment_var(domain, key, default_value = nil)
      domain_name = Reality::Naming.uppercase_constantize(domain.name)
      scope = self.app_scope
      code = self.env_code

      return ENV["#{domain_name}_#{scope}_#{key}_#{code}"] if scope && ENV["#{domain_name}_#{scope}_#{key}_#{code}"]
      return ENV["#{domain_name}_#{key}_#{code}"] if ENV["#{domain_name}_#{key}_#{code}"]
      return ENV["#{scope}_#{key}_#{code}"] if scope && ENV["#{scope}_#{key}_#{code}"]

      ENV["#{scope}_#{key}_#{code}"] ||
        ENV["#{key}_#{code}"] ||
        ENV[key] ||
        default_value
    end

    def env(key, default_value = nil)
      environment_var(key, default_value) || BuildrPlus.error("Unable to locate expected environment variable #{key}")
    end

    def environment_var(key, default_value = nil)
      scope = self.app_scope
      code = self.env_code

      return ENV["#{scope}_#{key}_#{code}"] if scope && ENV["#{scope}_#{key}_#{code}"]

      ENV["#{key}_#{code}"] ||
        ENV[key] ||
        default_value
    end

    def user
      ENV['USER']
    end

    def app_scope
      return ENV['APP_SCOPE'] if ENV['APP_SCOPE']
      return ENV['PRODUCT_VERSION'] if running_in_jenkins?
      nil
    end

    def running_in_jenkins?
      !!ENV['JOB_NAME']
    end

    def env_code(environment = self.environment)
      if environment == 'development'
        'DEV'
      elsif environment == 'test'
        'TEST'
      elsif environment == 'uat'
        'UAT'
      elsif environment == 'training'
        'TRN'
      elsif environment == 'ci'
        'CI'
      elsif environment == 'production'
        'PRD'
      else
        environment
      end
    end

    def db_scope
      if running_in_jenkins?
        "#{self.app_scope}_"
      else
        "#{user || 'NOBODY'}#{self.app_scope.nil? ? '' : "_#{self.app_scope}"}_"
      end
    end

    def load_application_config!
      @application_config = load_application_config unless @application_config
    end

    def reload_application_config!
      @application_config = nil
      load_application_config!
    end

    def get_buildr_project
      if ::Buildr.application.current_scope.size > 0
        ::Buildr.project(::Buildr.application.current_scope.join(':')) rescue nil
      else
        Buildr.projects[0]
      end
    end

    def output_aux_confgs!(config = application_config)
      emit_database_yml(config)
    end

    private

    def load_application_config
      if !File.exist?(self.application_config_location) && File.exist?(self.application_config_example_location)
        FileUtils.cp self.application_config_example_location, self.application_config_location
      end
      data = File.exist?(self.application_config_location) ?
        YAML::load(ERB.new(IO.read(self.application_config_location)).result) :
        {}

      config = BuildrPlus::Config::ApplicationConfig.new(data)

      populate_configuration(config)

      output_aux_confgs!(config)

      config
    end

    def emit_database_yml(config)
      if BuildrPlus::FeatureManager.activated?(:dbt)
        ::Dbt.repository.configuration_data = config.to_database_yml

        ::SSRS::Config.config_data = config.to_database_yml if BuildrPlus::FeatureManager.activated?(:rptman)

        # Also need to write file out for processes that pick up database.yml (like packaged
        # database definitions run via java -jar)
        FileUtils.mkdir_p File.dirname(::Dbt::Config.config_filename)
        File.open(::Dbt::Config.config_filename, 'wb') do |file|
          file.write "# DO NOT EDIT: File is auto-generated\n"
          file.write config.to_database_yml(:jruby => true).to_yaml
        end
      end
    end

    def emit_rails_configuration(domain)
      properties = BuildrPlus::Redfish.build_property_set(domain, BuildrPlus::Config.environment_config)

      base_directory = File.dirname(Buildr.application.buildfile.to_s)

      FileUtils.mkdir_p "#{base_directory}/config"
      File.open("#{base_directory}/config/config.properties", 'wb') do |file|
        file.write "# DO NOT EDIT: File is auto-generated\n"
        data = ''
        domain.data['custom_resources'].each_pair do |key, resource_config|
          value = resource_config['properties']['value']
          data += "#{key.gsub('/', '.')}=#{value}\n"
        end

        properties.each_pair do |key, value|
          data.gsub!("${#{key}}", value)
        end
        data = Redfish::Interpreter::Interpolater.interpolate_definition(domain, :data => data)[:data]
        file.write data
      end
    end

    def populate_configuration(config)
      %w(development test).each do |environment_key|
        config.environment(environment_key) unless config.environment_by_key?(environment_key)
        populate_environment_configuration(config.environment_by_key(environment_key), false)
      end
      copy_development_settings(config.environment_by_key('development'), config.environment_by_key('test'))
      config.environments.each do |environment|
        unless %w(development test).include?(environment.key.to_s)
          populate_environment_configuration(environment, true)
        end
      end
    end

    def copy_development_settings(from, to)
      from.settings.each_pair do |key, value|
        to.setting(key, value) unless to.setting?(key)
      end
    end

    def populate_environment_configuration(environment, check_only = false)
      populate_database_configuration(environment, check_only)
      populate_broker_configuration(environment, check_only)
      populate_keycloak_configuration(environment, check_only)
      populate_ssrs_configuration(environment, check_only)
      unless check_only
        populate_volume_configuration(environment)
        populate_settings(environment)
      end
    end

    def populate_settings(environment)
      if BuildrPlus::FeatureManager.activated?(:keycloak)
        BuildrPlus::Keycloak.client_types.each do |client_type|
          populate_keycloak_client_settings(environment, client_type, false)
        end
        BuildrPlus::Keycloak.external_client_types.keys.each do |client_type|
          populate_keycloak_client_settings(environment, client_type, true)
        end
        BuildrPlus::RemoteReferences.remote_datasources.each do |remote_datasource|
          populate_keycloak_remote_datasource_settings(environment, remote_datasource)
        end
      end
      if BuildrPlus::FeatureManager.activated?(:remote_references)
        BuildrPlus::RemoteReferences.remote_datasources.each do |remote_datasource|
          key = "#{Reality::Naming.uppercase_constantize(root_project.name)}_REPLICANT_CLIENT_#{Reality::Naming.uppercase_constantize(remote_datasource.name)}_URL"
          environment.setting(key, "http://127.0.0.1:8080/#{Reality::Naming.underscore(remote_datasource.name)}") unless environment.setting?(key)
        end
      end
      if BuildrPlus::FeatureManager.activated?(:remote_references)
        BuildrPlus::RemoteReferences.remote_datasources.each do |remote_datasource|
          key = "#{Reality::Naming.uppercase_constantize(root_project.name)}_REPLICANT_CLIENT_#{Reality::Naming.uppercase_constantize(remote_datasource.name)}_URL"
          environment.setting(key, "http://127.0.0.1:8080/#{Reality::Naming.underscore(remote_datasource.name)}") unless environment.setting?(key)
        end
      end
      if BuildrPlus::FeatureManager.activated?(:gwt)
        prefix = "#{Reality::Naming.uppercase_constantize(root_project.name)}_CODE_SERVER_"
        environment.setting("#{prefix}HOST", 'localhost')
        environment.setting("#{prefix}PORT", '8889')
      end
    end

    def populate_keycloak_remote_datasource_settings(environment, remote_datasource)
      prefix = "#{Reality::Naming.uppercase_constantize(root_project.name)}_REPLICANT_CLIENT_#{Reality::Naming.uppercase_constantize(remote_datasource.name)}_KEYCLOAK_"
      environment.setting("#{prefix}SERVER_URL", environment.keycloak.base_url) unless environment.setting?("#{prefix}SERVER_URL")
      environment.setting("#{prefix}REALM", environment.keycloak.realm) unless environment.setting?("#{prefix}REALM")

      # Assume that by default the remote data source uses same keycloak realm but uses this
      # apps client as the remote app is often configured with a bearer only client
      environment.setting("#{prefix}CLIENT", BuildrPlus::Keycloak.client_name_for(root_project.name, false)) unless environment.setting?("#{prefix}CLIENT")
      environment.setting("#{prefix}USERNAME", environment.keycloak.service_username) unless environment.setting?("#{prefix}USERNAME")
      environment.setting("#{prefix}PASSWORD", environment.keycloak.service_password) unless environment.setting?("#{prefix}PASSWORD")
    end

    def populate_keycloak_client_settings(environment, client_type, external)
      prefix = BuildrPlus::Keycloak.keycloak_config_prefix(client_type, external)
      environment.setting("#{prefix}_KEYCLOAK_REALM", environment.keycloak.realm) unless environment.setting?("#{prefix}_KEYCLOAK_REALM")
      environment.setting("#{prefix}_KEYCLOAK_REALM_PUBLIC_KEY", environment.keycloak.public_key) unless environment.setting?("#{prefix}_KEYCLOAK_REALM_PUBLIC_KEY")
      environment.setting("#{prefix}_KEYCLOAK_AUTH_SERVER_URL", environment.keycloak.base_url) unless environment.setting?("#{prefix}_KEYCLOAK_AUTH_SERVER_URL")
      environment.setting("#{prefix}_KEYCLOAK_CLIENT_NAME", BuildrPlus::Keycloak.client_name_for(client_type, external)) unless environment.setting?("#{prefix}_KEYCLOAK_CLIENT_NAME")
    end

    def populate_volume_configuration(environment)
      buildr_project = get_buildr_project.root_project
      if BuildrPlus::FeatureManager.activated?(:redfish)
        domain = Redfish.domain_by_key(buildr_project.name)

        domain.volume_requirements.keys.each do |key|
          environment.set_volume(key, "volumes/#{key}") unless environment.volume?(key)
        end
      end
      base_directory = File.dirname(::Buildr.application.buildfile.to_s)
      environment.volumes.each_pair do |key, local_path|
        environment.set_volume(key, File.expand_path(local_path, base_directory))
      end
    end

    def populate_database_configuration(environment, check_only)
      if !BuildrPlus::FeatureManager.activated?(:dbt) && !environment.databases.empty?
        raise "Databases defined in application configuration but BuildrPlus facet 'dbt' not enabled"
      elsif BuildrPlus::FeatureManager.activated?(:dbt)
        # Ensure all databases are registered in dbt
        environment.databases.each do |database|
          unless ::Dbt.database_for_key?(database.key)
            raise "Database '#{database.key}' defined in application configuration but has not been defined as a dbt database"
          end
        end
        # Create database configurations if in Dbt but configuration does not already exist
        ::Dbt.repository.database_keys.each do |database_key|
          environment.database(database_key) unless environment.database_by_key?(database_key)
        end unless check_only

        buildr_project = get_buildr_project

        environment.databases.each do |database|
          dbt_database = ::Dbt.database_for_key(database.key)
          dbt_imports =
            !dbt_database.imports.empty? ||
              (dbt_database.packaged? && dbt_database.extra_actions.any? { |a| a.to_s =~ /import/ })

          environment.databases.select { |d| d != database }.each do |d|
            ::Dbt.database_for_key(d.key).filters.each do |f|
              if f.is_a?(Struct::DatabaseNameFilter) && f.database_key.to_s == database.key.to_s
                dbt_imports = true
              end
            end
          end unless dbt_imports

          is_sql_server = database.is_a?(BuildrPlus::Config::MssqlDatabaseConfig)
          short_name = Reality::Naming.uppercase_constantize(database.key.to_s == 'default' ? buildr_project.root_project.name : database.key.to_s)
          database.database = "#{BuildrPlus::Config.db_scope}#{short_name}_#{self.env_code(environment.key)}" unless database.database
          database.import_from = "PROD_CLONE_#{short_name}" unless database.import_from || !dbt_imports
          type_prefix = is_sql_server ? 'MS' : 'PG'
          database.host = environment_var("#{type_prefix}_DB_SERVER_HOST") unless database.host
          unless database.port_set?
            port = environment_var("#{type_prefix}_DB_SERVER_PORT", database.port)
            database.port = port.to_i if port
          end
          database.admin_username = environment_var("#{type_prefix}_DB_SERVER_USERNAME") unless database.admin_username
          database.admin_password = environment_var("#{type_prefix}_DB_SERVER_PASSWORD") unless database.admin_password

          if is_sql_server
            database.restore_name = short_name unless database.restore_name
            database.backup_name = short_name unless database.backup_name
            database.backup_location = environment_var("#{type_prefix}_DB_BACKUPS_LOCATION") unless database.backup_location
            database.delete_backup_history = (environment_var("#{type_prefix}_DB_SERVER_DELETE_BACKUP_HISTORY", 'true') == 'true') unless database.delete_backup_history_set?
            unless database.instance
              instance = environment_var("#{type_prefix}_DB_SERVER_INSTANCE", '')
              database.instance = instance unless instance == ''
            end
          end

          raise "Configuration for database key #{database.key} is missing host attribute and can not be derived from environment variable #{type_prefix}_DB_SERVER_HOST" unless database.host
          raise "Configuration for database key #{database.key} is missing admin_username attribute and can not be derived from environment variable #{type_prefix}_DB_SERVER_USERNAME" unless database.admin_username
          raise "Configuration for database key #{database.key} is missing admin_password attribute and can not be derived from environment variable #{type_prefix}_DB_SERVER_PASSWORD" unless database.admin_password
          raise "Configuration for database key #{database.key} specifies import_from but dbt defines no import for database" if database.import_from && !dbt_imports
        end
      end
    end

    def populate_ssrs_configuration(environment, check_only)
      endpoint = BuildrPlus::Config.environment_var('RPTMAN_ENDPOINT')
      domain = BuildrPlus::Config.environment_var('RPTMAN_DOMAIN')
      username = BuildrPlus::Config.environment_var('RPTMAN_USERNAME')
      password = BuildrPlus::Config.environment_var('RPTMAN_PASSWORD')

      if !BuildrPlus::FeatureManager.activated?(:rptman) && environment.ssrs?
        raise "Ssrs defined in application configuration but BuildrPlus facet 'rptman' not enabled"
      elsif BuildrPlus::FeatureManager.activated?(:rptman) && !environment.ssrs? && !check_only
        environment.ssrs
      elsif !BuildrPlus::FeatureManager.activated?(:rptman) && !environment.ssrs?
        return
      elsif BuildrPlus::FeatureManager.activated?(:rptman) && !environment.ssrs? && check_only
        return
      end

      scope = self.app_scope

      environment.ssrs.report_target = endpoint if environment.ssrs.report_target.nil?
      environment.ssrs.domain = domain if environment.ssrs.domain.nil?
      environment.ssrs.admin_username = username if environment.ssrs.admin_username.nil?
      environment.ssrs.admin_password = password if environment.ssrs.admin_password.nil?

      if environment.ssrs.prefix.nil?
        buildr_project = get_buildr_project
        short_name = Reality::Naming.uppercase_constantize(buildr_project.root_project.name)
        environment.ssrs.prefix = "/Auto/#{user || 'NOBODY'}#{scope.nil? ? '' : "_#{scope}"}/#{self.env_code}/#{short_name}"
      end

      raise 'Configuration for ssrs is missing report_target attribute and can not be derived from environment variable RPTMAN_ENDPOINT' unless environment.ssrs.report_target
      raise 'Configuration for ssrs is missing domain attribute and can not be derived from environment variable RPTMAN_DOMAIN' unless environment.ssrs.domain
      raise 'Configuration for ssrs is missing admin_username attribute and can not be derived from environment variable RPTMAN_USERNAME' unless environment.ssrs.admin_username
      raise 'Configuration for ssrs is missing admin_password attribute and can not be derived from environment variable RPTMAN_PASSWORD' unless environment.ssrs.admin_password
    end

    def populate_broker_configuration(environment, check_only)
      if BuildrPlus::FeatureManager.activated?(:jms) && BuildrPlus::FeatureManager.activated?(:docker)
        BuildrPlus::Jms.link_container_to_configuration(BuildrPlus::Config.get_buildr_project, environment)
      end
      if !environment.broker? && !check_only
        host = BuildrPlus::Config.environment_var('OPENMQ_HOST', 'localhost')
        port = BuildrPlus::Config.environment_var('OPENMQ_PORT', 7676)
        username = BuildrPlus::Config.environment_var('OPENMQ_ADMIN_USERNAME', 'admin')
        password = BuildrPlus::Config.environment_var('OPENMQ_ADMIN_PASSWORD', 'admin')

        environment.broker(:host => host, :port => port, :admin_username => username, :admin_password => password)
      end
    end

    def populate_keycloak_configuration(environment, check_only)
      if !BuildrPlus::FeatureManager.activated?(:keycloak) && environment.keycloak?
        raise "Keycloak defined in application configuration but BuildrPlus facet 'keycloak' not enabled"
      elsif BuildrPlus::FeatureManager.activated?(:keycloak) && !environment.keycloak? && !check_only

        base_url = BuildrPlus::Config.environment_var('KEYCLOAK_AUTH_SERVER_URL')
        public_key = BuildrPlus::Config.environment_var('KEYCLOAK_REALM_PUBLIC_KEY')
        realm = BuildrPlus::Config.environment_var('KEYCLOAK_REALM')
        username = BuildrPlus::Config.environment_var('KEYCLOAK_ADMIN_USERNAME')
        password = BuildrPlus::Config.environment_var('KEYCLOAK_ADMIN_PASSWORD')
        service_username = BuildrPlus::Config.environment_var('KEYCLOAK_SERVICE_USERNAME')
        service_password = BuildrPlus::Config.environment_var('KEYCLOAK_SERVICE_PASSWORD')

        environment.keycloak.base_url = base_url if environment.keycloak.base_url.nil?
        environment.keycloak.public_key = public_key if environment.keycloak.public_key.nil?
        environment.keycloak.realm = realm if environment.keycloak.realm.nil?
        environment.keycloak.admin_username = username if environment.keycloak.admin_username.nil?
        environment.keycloak.admin_password = password if environment.keycloak.admin_password.nil?
        environment.keycloak.service_username = service_username if environment.keycloak.service_username.nil?
        environment.keycloak.service_password = service_password if environment.keycloak.service_password.nil?

        raise 'Configuration for keycloak is missing base_url attribute and can not be derived from environment variable KEYCLOAK_AUTH_SERVER_URL' unless environment.keycloak.base_url
        raise 'Configuration for keycloak is missing public_key attribute and can not be derived from environment variable KEYCLOAK_REALM_PUBLIC_KEY' unless environment.keycloak.public_key
        raise 'Configuration for keycloak is missing realm attribute and can not be derived from environment variable KEYCLOAK_REALM' unless environment.keycloak.realm
        raise 'Configuration for keycloak is missing admin_password attribute and can not be derived from environment variable KEYCLOAK_ADMIN_PASSWORD' unless environment.keycloak.admin_password
      end
    end
  end
  f.enhance(:ProjectExtension) do
    after_define do |project|

      if project.ipr?
        project.task(':domgen:all' => ['config:expand_application_yml']) if BuildrPlus::FeatureManager.activated?(:domgen)

        desc 'Generate a complete application configuration from context'
        project.task(':config:expand_application_yml') do
          filename = project._('generated/buildr_plus/config/application.yml')
          trace("Expanding application configuration to #{filename}")
          FileUtils.mkdir_p File.dirname(filename)
          File.open(filename, 'wb') do |file|
            file.write "# DO NOT EDIT: File is auto-generated\n"
            file.write BuildrPlus::Config.application_config.to_h.to_yaml
          end
          database_filename = project._('generated/buildr_plus/config/database.yml')
          trace("Expanding database configuration to #{database_filename}")
          File.open(database_filename, 'wb') do |file|
            file.write "# DO NOT EDIT: File is auto-generated\n"
            file.write BuildrPlus::Config.application_config.to_database_yml.to_yaml
          end
        end
      end
    end
  end
end


text:
package dytnsapi

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// DataList is a nested struct in dytnsapi response
type DataList struct {
	Code   string `json:"Code" xml:"Code"`
	Status string `json:"Status" xml:"Status"`
	Number string `json:"Number" xml:"Number"`
}


text:
package au.com.windyroad.hateoas.core;

import java.net.URISyntaxException;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

import au.com.windyroad.hateoas.core.entities.CreatedEntity;
import au.com.windyroad.hateoas.core.entities.EntityWrapper;
import au.com.windyroad.hateoas.core.entities.UpdatedEntity;

public interface Resolver {

    public CompletableFuture<CreatedEntity> create(Link link,
            Map<String, Object> filteredParameters);

    public CompletableFuture<Void> delete(Link link,
            Map<String, Object> filteredParameters);

    public CompletableFuture<EntityWrapper<?>> get(Link link,
            Map<String, Object> filteredParameters);

    public CompletableFuture<UpdatedEntity> update(Link link,
            Map<String, Object> filteredParameters);

    public <E> CompletableFuture<E> get(String path, Class<E> type)
            throws URISyntaxException;

}


text:
package org.elasticsearch.painless;

import java.util.BitSet;
import java.util.HashMap;
import java.util.Map;

/**
 * Program-wide globals (initializers, synthetic methods, etc)
 */
public class Globals {
    private final Map<String,Constant> constantInitializers = new HashMap<>();
    private final BitSet statements;

    /** Create a new Globals from the set of statement boundaries */
    public Globals(BitSet statements) {
        this.statements = statements;
    }

    /** Adds a new constant initializer to be written */
    public void addConstantInitializer(Constant constant) {
        if (constantInitializers.put(constant.name, constant) != null) {
            throw new IllegalStateException("constant initializer: " + constant.name + " already exists");
        }
    }

    /** Returns the current initializers */
    public Map<String,Constant> getConstantInitializers() {
        return constantInitializers;
    }

    /** Returns the set of statement boundaries */
    public BitSet getStatements() {
        return statements;
    }
}