text:
Vector< SimObjectPtr<SceneObject> > AccumulationVolume::smAccuObjects;
Vector< SimObjectPtr<AccumulationVolume> > AccumulationVolume::smAccuVolumes;

GFXTexHandle gLevelAccuMap;

//#define DEBUG_DRAW

IMPLEMENT_CO_NETOBJECT_V1( AccumulationVolume );

ConsoleDocClass( AccumulationVolume,
   "@brief An invisible shape that allow objects within it to have an accumulation map.\n\n"

   "AccumulationVolume is used to add additional realism to a scene. It's main use is in outdoor scenes "
   " where objects could benefit from overlaying environment accumulation textures such as sand, snow, etc.\n\n"

   "Objects within the volume must have accumulation enabled in their material. \n\n"

   "@ingroup enviroMisc"
);

//-----------------------------------------------------------------------------

AccumulationVolume::AccumulationVolume()
   : mTransformDirty( true ),
     mSilhouetteExtractor( mPolyhedron )
{
   VECTOR_SET_ASSOCIATION( mWSPoints );
   VECTOR_SET_ASSOCIATION( mVolumeQueryList );

   //mObjectFlags.set( VisualOccluderFlag );

   mNetFlags.set( Ghostable | ScopeAlways );
   mObjScale.set( 1.f, 1.f, 1.f );
   mObjBox.set(
      Point3F( -0.5f, -0.5f, -0.5f ),
      Point3F( 0.5f, 0.5f, 0.5f )
   );

   mObjToWorld.identity();
   mWorldToObj.identity();

   // Accumulation Texture.
   mTextureName = "";
   mAccuTexture = NULL;

   resetWorldBox();
}

AccumulationVolume::~AccumulationVolume()
{
   mAccuTexture = NULL;
}

void AccumulationVolume::initPersistFields()
{
   addProtectedField( "texture", TypeStringFilename, Offset( mTextureName, AccumulationVolume ),
         &_setTexture, &defaultProtectedGetFn, "Accumulation texture." );

   Parent::initPersistFields();
}

//-----------------------------------------------------------------------------

void AccumulationVolume::consoleInit()
{
   // Disable rendering of occlusion volumes by default.
   getStaticClassRep()->mIsRenderEnabled = false;
}

//-----------------------------------------------------------------------------

bool AccumulationVolume::onAdd()
{
   if( !Parent::onAdd() )
      return false;

   // Prepare some client side things.
   if ( isClientObject() )
   {
      smAccuVolumes.push_back(this);
      refreshVolumes();
   }

   // Set up the silhouette extractor.
   mSilhouetteExtractor = SilhouetteExtractorType( mPolyhedron );

   return true;
}

void AccumulationVolume::onRemove()
{
   if ( isClientObject() )
   {
      smAccuVolumes.remove(this);
      refreshVolumes();
   }
   Parent::onRemove();
}

//-----------------------------------------------------------------------------

void AccumulationVolume::_renderObject( ObjectRenderInst* ri, SceneRenderState* state, BaseMatInstance* overrideMat )
{
   Parent::_renderObject( ri, state, overrideMat );

   #ifdef DEBUG_DRAW
   if( state->isDiffusePass() )
      DebugDrawer::get()->drawPolyhedronDebugInfo( mPolyhedron, getTransform(), getScale() );
   #endif
}

//-----------------------------------------------------------------------------

void AccumulationVolume::setTransform( const MatrixF& mat )
{
   Parent::setTransform( mat );
   mTransformDirty = true;
   refreshVolumes();
}

//-----------------------------------------------------------------------------

void AccumulationVolume::buildSilhouette( const SceneCameraState& cameraState, Vector< Point3F >& outPoints )
{
   // Extract the silhouette of the polyhedron.  This works differently
   // depending on whether we project orthogonally or in perspective.

   TempAlloc< U32 > indices( mPolyhedron.getNumPoints() );
   U32 numPoints;

   if( cameraState.getFrustum().isOrtho() )
   {
      // Transform the view direction into object space.

      Point3F osViewDir;
      getWorldTransform().mulV( cameraState.getViewDirection(), &osViewDir );

      // And extract the silhouette.

      SilhouetteExtractorOrtho< PolyhedronType > extractor( mPolyhedron );
      numPoints = extractor.extractSilhouette( osViewDir, indices, indices.size );
   }
   else
   {
      // Create a transform to go from view space to object space.

      MatrixF camView( true );
      camView.scale( Point3F( 1.0f / getScale().x, 1.0f / getScale().y, 1.0f / getScale().z ) );
      camView.mul( getRenderWorldTransform() );
      camView.mul( cameraState.getViewWorldMatrix() );

      // Do a perspective-correct silhouette extraction.

      numPoints = mSilhouetteExtractor.extractSilhouette(
         camView,
         indices, indices.size );
   }

   // If we haven't yet, transform the polyhedron's points
   // to world space.

   if( mTransformDirty )
   {
      const U32 numPoints = mPolyhedron.getNumPoints();
      const PolyhedronType::PointType* points = getPolyhedron().getPoints();

      mWSPoints.setSize( numPoints );
      for( U32 i = 0; i < numPoints; ++ i )
      {
         Point3F p = points[ i ];
         p.convolve( getScale() );
         getTransform().mulP( p, &mWSPoints[ i ] );
      }

      mTransformDirty = false;
   }

   // Now store the points.

   outPoints.setSize( numPoints );
   for( U32 i = 0; i < numPoints; ++ i )
      outPoints[ i ] = mWSPoints[ indices[ i ] ];
}

//-----------------------------------------------------------------------------

U32 AccumulationVolume::packUpdate( NetConnection *connection, U32 mask, BitStream *stream )
{
   U32 retMask = Parent::packUpdate( connection, mask, stream );

   if (stream->writeFlag(mask & InitialUpdateMask))
   {
      stream->write( mTextureName );
   }

   return retMask;
}

void AccumulationVolume::unpackUpdate( NetConnection *connection, BitStream *stream )
{
   Parent::unpackUpdate( connection, stream );

   if (stream->readFlag())
   {
      stream->read( &mTextureName );
      setTexture(mTextureName);
   }
}

//-----------------------------------------------------------------------------

void AccumulationVolume::inspectPostApply()
{
   Parent::inspectPostApply();
   setMaskBits(U32(-1) );
}

void AccumulationVolume::setTexture( const String& name )
{
   mTextureName = name;
   if ( isClientObject() && mTextureName.isNotEmpty() )
   {
      mAccuTexture.set(mTextureName, &GFXDefaultStaticDiffuseProfile, "AccumulationVolume::mAccuTexture");
      if ( mAccuTexture.isNull() )
         Con::warnf( "AccumulationVolume::setTexture - Unable to load texture: %s", mTextureName.c_str() );
   }
   refreshVolumes();
}

//-----------------------------------------------------------------------------
// Static Functions
//-----------------------------------------------------------------------------
bool AccumulationVolume::_setTexture( void *object, const char *index, const char *data )
{
   AccumulationVolume* volume = reinterpret_cast< AccumulationVolume* >( object );
   volume->setTexture( data );
   return false;
}

void AccumulationVolume::refreshVolumes()
{
   // This function tests each accumulation object to
   // see if it's within the bounds of an accumulation
   // volume. If so, it will pass on the accumulation
   // texture of the volume to the object.

   // This function should only be called when something
   // global like change of volume or material occurs.

   // Clear old data.
   for (S32 n = 0; n < smAccuObjects.size(); ++n)
   {
      SimObjectPtr<SceneObject> object = smAccuObjects[n];
      if ( object.isValid() )
         object->mAccuTex = gLevelAccuMap;
   }

   //
   for (S32 i = 0; i < smAccuVolumes.size(); ++i)
   {
      SimObjectPtr<AccumulationVolume> volume = smAccuVolumes[i];
      if ( volume.isNull() ) continue;

      for (S32 n = 0; n < smAccuObjects.size(); ++n)
      {
         SimObjectPtr<SceneObject> object = smAccuObjects[n];
         if ( object.isNull() ) continue;

         if ( volume->containsPoint(object->getPosition()) )
            object->mAccuTex = volume->mAccuTexture;
      }
   }
}

// Accumulation Object Management.
void AccumulationVolume::addObject(SimObjectPtr<SceneObject> object)
{
   smAccuObjects.push_back(object);
   refreshVolumes();
}

void AccumulationVolume::removeObject(SimObjectPtr<SceneObject> object)
{
   smAccuObjects.remove(object);
   refreshVolumes();
}

void AccumulationVolume::updateObject(SceneObject* object)
{
   // This function is called when an individual object
   // has been moved. Tests to see if it's in any of the
   // accumulation volumes.

   // We use ZERO instead of NULL so the accumulation
   // texture will be updated in renderMeshMgr.
   object->mAccuTex = gLevelAccuMap;

   for (S32 i = 0; i < smAccuVolumes.size(); ++i)
   {
      SimObjectPtr<AccumulationVolume> volume = smAccuVolumes[i];
      if ( volume.isNull() ) continue;

      if ( volume->containsPoint(object->getPosition()) )
         object->mAccuTex = volume->mAccuTexture;
   }
}


text:
using System;

namespace spaar.Mods.KeyManager
{
  public class Keybinding
  {
    public int MKeyIndex { get; private set; }
    public Guid Guid { get; private set; }

    public int KeyCodeIndex { get; private set; }

    public MKey Key => Block.Keys[MKeyIndex];

    public BlockBehaviour Block
    {
      get { return Machine.Active().BuildingBlocks.Find(b => b.Guid == Guid); }
    }

    public Keybinding(BlockBehaviour block, int mKeyIndex, int keyCodeIndex) : this(block.Guid, mKeyIndex, keyCodeIndex)
    {
    }

    public Keybinding(Guid guid, int mKeyIndex, int keyCodeIndex)
    {
      Guid = guid;
      MKeyIndex = mKeyIndex;
      KeyCodeIndex = keyCodeIndex;
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
"""
Package for generation of content, AKA, Baking things.
"""


text:
using System;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.Interactions;
using NakedFramework.Core.Error;

namespace NakedFramework.Metamodel.Facet;

[Serializable]
public abstract class DisabledFacetAbstract : SingleWhenValueFacetAbstract, IDisabledFacet {
    protected DisabledFacetAbstract(WhenTo when) : base(when) { }

    public override Type FacetType => typeof(IDisabledFacet);

    #region IDisabledFacet Members

    public virtual string Disables(IInteractionContext ic) => DisabledReason(ic.Target);

    public virtual Exception CreateExceptionFor(IInteractionContext ic) => new DisabledException(ic, Disables(ic));

    public abstract string DisabledReason(INakedObjectAdapter nakedObjectAdapter);

    #endregion
}


text:
package org.python;

public interface Object {

    /**
     * Return the python name for this class.
     */
    public java.lang.String getPythonName();

    /**
     * Python interface compatibility
     * Section 3.3.1 - Basic customization
     */

    // public void __new__(); {
    // }

    // public void __init__(); {
    // }

    public void __del__();

    public org.python.types.Str __repr__();

    public org.python.types.Str __str__();

    public org.python.types.Bytes __bytes__();

    public org.python.types.Str __format__();

    public org.python.Object __lt__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __lt__(org.python.Object other);

    public org.python.Object __le__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __le__(org.python.Object other);

    public org.python.Object __eq__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __eq__(org.python.Object other);

    public org.python.Object __ne__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __ne__(org.python.Object other);

    public org.python.Object __gt__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __gt__(org.python.Object other);

    public org.python.Object __ge__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __ge__(org.python.Object other);

    public org.python.types.Int __hash__();

    public org.python.types.Bool __bool__();

    /**
     * Section 3.3.2 - Emulating container types
     */
    // The cast back from java Object to Hashtable is, strictly speaking,
    // unchecked, but given we know it's an Object, we know value is a Map.
    public org.python.Object __getattr__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __getattr__(org.python.Object name);
    public org.python.Object __getattr__(java.lang.String name);

    public org.python.Object __getattribute__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __getattribute__(org.python.Object name);
    public org.python.Object __getattribute__(java.lang.String name);

    public void __setattr__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __setattr__(org.python.Object name, org.python.Object value);
    public void __setattr__(java.lang.String name, org.python.Object value);

    public void __delattr__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __delattr__(org.python.Object name);
    public void __delattr__(java.lang.String name);

    public org.python.types.List __dir__();

    /**
     * Section 3.3.4 - Customizing instance and subclass checks
     */
    public org.python.Object __instancecheck__(org.python.Object instance);

    public org.python.Object __subclasscheck__(org.python.Object subclass);

    /**
     * Section 3.3.5 - Emulating callable objects
     */
    public org.python.Object __call__(org.python.Object... args);

    /**
     * Section 3.3.6 - Emulating container types
     */

    public org.python.types.Int __len__();

    public org.python.types.Int __length_hint__();

    public org.python.Object __getitem__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __getitem__(org.python.Object index);
    public org.python.Object __getitem__(int index);

    public org.python.Object __missing__(org.python.Object key);

    public void __setitem__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __setitem__(org.python.Object index, org.python.Object value);
    public void __setitem__(int index, org.python.Object value);

    public org.python.Iterable __iter__();

    public org.python.Iterable __reversed__();

    public org.python.types.Bool __contains__(org.python.Object item);

    /**
     * Section 3.3.7 - Emulating numeric types
     */

    public org.python.Object __add__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __add__(org.python.Object other);

    public org.python.Object __sub__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __sub__(org.python.Object other);

    public org.python.Object __mul__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __mul__(org.python.Object other);

    public org.python.Object __truediv__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __truediv__(org.python.Object other);

    public org.python.Object __floordiv__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __floordiv__(org.python.Object other);

    public org.python.Object __mod__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __mod__(org.python.Object other);

    public org.python.Object __divmod__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __divmod__(org.python.Object other);

    public org.python.Object __pow__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __pow__(org.python.Object other);

    public org.python.Object __lshift__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __lshift__(org.python.Object other);

    public org.python.Object __rshift__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rshift__(org.python.Object other);

    public org.python.Object __and__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __and__(org.python.Object other);

    public org.python.Object __xor__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __xor__(org.python.Object other);

    public org.python.Object __or__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __or__(org.python.Object other);

    public org.python.Object __radd__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __radd__(org.python.Object other);

    public org.python.Object __rsub__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rsub__(org.python.Object other);

    public org.python.Object __rmul__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rmul__(org.python.Object other);

    public org.python.Object __rtruediv__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rtruediv__(org.python.Object other);

    public org.python.Object __rfloordiv__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rfloordiv__(org.python.Object other);

    public org.python.Object __rmod__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rmod__(org.python.Object other);

    public org.python.Object __rdivmod__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rdivmod__(org.python.Object other);

    public org.python.Object __rpow__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rpow__(org.python.Object other);

    public org.python.Object __rlshift__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rlshift__(org.python.Object other);

    public org.python.Object __rrshift__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rrshift__(org.python.Object other);

    public org.python.Object __rand__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rand__(org.python.Object other);

    public org.python.Object __rxor__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __rxor__(org.python.Object other);

    public org.python.Object __ror__(org.python.Object [] args, java.util.Hashtable kwargs);
    public org.python.Object __ror__(org.python.Object other);

    public void __iadd__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __iadd__(org.python.Object other);

    public void __isub__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __isub__(org.python.Object other);

    public void __imul__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __imul__(org.python.Object other);

    public void __itruediv__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __itruediv__(org.python.Object other);

    public void __ifloordiv__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __ifloordiv__(org.python.Object other);

    public void __imod__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __imod__(org.python.Object other);

    public void __ipow__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __ipow__(org.python.Object other);

    public void __ilshift__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __ilshift__(org.python.Object other);

    public void __irshift__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __irshift__(org.python.Object other);

    public void __iand__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __iand__(org.python.Object other);

    public void __ixor__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __ixor__(org.python.Object other);

    public void __ior__(org.python.Object [] args, java.util.Hashtable kwargs);
    public void __ior__(org.python.Object other);

    public org.python.Object __neg__();
    public org.python.Object __pos__();
    public org.python.Object __abs__();
    public org.python.Object __invert__();

    public org.python.Object __not__();
    public org.python.Object __complex__(org.python.Object [] args, java.util.Hashtable kwargs);

    public org.python.types.Int __int__();
    public org.python.types.Float __float__();
    public org.python.Object __round__();

    /**
     * Section 3.3.8 - With statement context
     */
    public org.python.Object __enter__();
    public org.python.Object __exit__(org.python.Object exc_type, org.python.Object exc_value, org.python.Object traceback);

}


text:
<?php

namespace Seboettg\Collection\NativePhp;

use ReturnTypeWillChange;

trait IteratorTrait
{
    private int $offset = 0;
    /**
     * {@inheritdoc}
     */
    #[ReturnTypeWillChange]
    public function current()
    {
        return $this->valid() ? $this->array[$this->offset] : false;
    }

    public function key(): int
    {
        return $this->offset;
    }

    /**
     * {@inheritdoc}
     */
    public function next(): void
    {
        ++$this->offset;
    }

    public function valid(): bool
    {
        return isset($this->array[$this->offset]);
    }

    public function rewind(): void
    {
        $this->offset = 0;
    }
}


text:
namespace _02.HornetComm
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class HornetComm
    {
        public static void Main()
        {

            Dictionary<string, List<string>> broadcasts = new Dictionary<string, List<string>>();
            Dictionary<string, List<string>> messages = new Dictionary<string, List<string>>();

            while (true)
            {
                string input = Console.ReadLine();
                if (input == "Hornet is Green")
                {
                    break;
                }

                string[] tokens = input.Split(new[] { " <-> " }, StringSplitOptions.RemoveEmptyEntries);

                if (tokens.Length != 2)
                {
                    continue;
                }

                string firstQuery = tokens[0];
                string secondQuery = tokens[1];

                if (firstQuery.All(char.IsDigit) && secondQuery.All(char.IsLetterOrDigit))
                {
                    //private message
                    string recipientsData = ReverseString(firstQuery);
                    string message = secondQuery;
                    if (!messages.ContainsKey(recipientsData))
                    {
                        messages[recipientsData] = new List<string>();
                    }
                    messages[recipientsData].Add(message);
                }
                else if (!firstQuery.Any(char.IsDigit) && secondQuery.All(char.IsLetterOrDigit))
                {
                    //broadcast
                    string message = firstQuery;
                    string frequency = "";
                    char[] temp = secondQuery.ToCharArray();
                    foreach (char @char in temp)
                    {
                        if (char.IsLower(@char))
                        {
                            frequency = frequency + char.ToUpper(@char);
                        }
                        else
                        {
                            frequency = frequency + char.ToLower(@char);
                        }
                    }

                    if (!broadcasts.ContainsKey(frequency))
                    {
                        broadcasts[frequency] = new List<string>();
                    }
                    broadcasts[frequency].Add(message);
                }
                else
                {
                    continue;
                }
            }
            Console.WriteLine("Broadcasts:");

            if (broadcasts.Count != 0)
            {
                foreach (var broadcast in broadcasts)
                {
                    string frequency = broadcast.Key;
                    List<string> broadcastsMessages = broadcast.Value;

                    foreach (var broadcastMessage in broadcastsMessages)
                    {
                        Console.WriteLine($"{frequency} -> {broadcastMessage}");
                    }
                }
            }
            else
            {
                Console.WriteLine("None");
            }

            Console.WriteLine("Messages:");
            if (messages.Count != 0)
            {
                foreach (var message in messages)
                {
                    string recipient = message.Key;
                    List<string> recipientMessages = message.Value;

                    foreach (var recipientMessage in recipientMessages)
                    {
                        Console.WriteLine($"{recipient} -> {recipientMessage}");
                    }
                }
            }
            else
            {
                Console.WriteLine("None");
            }

        }

        public static string ReverseString(string s)
        {
            char[] charArray = s.ToCharArray();
            Array.Reverse(charArray);
            return new string(charArray);
        }
    }
}


text:
#import <Foundation/Foundation.h>
#import "CDVAdMobAds.h"
#import <GoogleMobileAds/GADRewardBasedVideoAdDelegate.h>
#import <GoogleMobileAds/GADExtras.h>

@class CDVAdMobAds;

@interface CDVAdMobAdsRewardedAdListener : NSObject <GADRewardBasedVideoAdDelegate> {

}

@property (nonatomic, retain) CDVAdMobAds *adMobAds;
@property (assign) BOOL isBackFill;

- (instancetype)initWithAdMobAds: (CDVAdMobAds *)originalAdMobAds andIsBackFill: (BOOL)andIsBackFill;
- (void)rewardBasedVideoAdDidFailedToShow:(GADRewardBasedVideoAd *) rewarded;

@end


text:
package edu.dpacademy.strategy;

public class SearchManager {

    private Searchable searchable;

    public SearchManager(Searchable searchable) {
        this.searchable = searchable;
    }

    public Searchable getSearchable() {
        return searchable;
    }

    public void setSearchable(Searchable searchable) {
        this.searchable = searchable;
    }

    public int getSearchResult(int[] array, int element) {
        return this.searchable.search(array, element);
    }

}


text:
// This module provides internal functions for dynamic expressions in OData V4 annotations. It is a
// helper module for sap.ui.model.odata.AnnotationHelper.
sap.ui.define([
	'jquery.sap.global', './_AnnotationHelperBasics', 'sap/ui/base/BindingParser',
	'sap/ui/base/ManagedObject', 'sap/ui/core/format/DateFormat', 'sap/ui/model/odata/ODataUtils'
], function(jQuery, Basics, BindingParser, ManagedObject, DateFormat, ODataUtils) {
	'use strict';

	// see http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/abnf/odata-abnf-construction-rules.txt
	var sAnnotationHelper = "sap.ui.model.odata.AnnotationHelper",
		sDateValue = "\\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\d|3[01])",
		sDecimalValue = "[-+]?\\d+(?:\\.\\d+)?",
		sMaxSafeInteger = "9007199254740991",
		sMinSafeInteger = "-" + sMaxSafeInteger,
		aPerformanceCategories = [sAnnotationHelper],
		sPerformanceGetExpression = sAnnotationHelper + "/getExpression",
		sTimeOfDayValue = "(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(\\.\\d{1,12})?)?",
		mEdmType2RegExp = {
			Bool : /^true$|^false$/i,
			// Note: 'NaN' and 'INF' are case sensitive, "e" is not!
			Float : new RegExp("^" + sDecimalValue + "(?:[eE][-+]?\\d+)?$|^NaN$|^-INF$|^INF$"),
			Date : new RegExp("^" + sDateValue + "$"),
			DateTimeOffset : new RegExp("^" + sDateValue + "T" + sTimeOfDayValue
				+ "(?:Z|[-+](?:0\\d|1[0-3]):[0-5]\\d|[-+]14:00)$", "i"),
			Decimal : new RegExp("^" + sDecimalValue + "$"),
			Guid : /^[A-F0-9]{8}-(?:[A-F0-9]{4}-){3}[A-F0-9]{12}$/i,
			Int : /^[-+]?\d{1,19}$/,
			TimeOfDay : new RegExp("^" + sTimeOfDayValue + "$")
		},
		Expression,
		// a simple binding (see sap.ui.base.BindingParser.simpleParser) to "@i18n" model
		// w/o bad chars (see _AnnotationHelperBasics: rBadChars) inside path!
		rI18n = /^\{@i18n>[^\\\{\}:]+\}$/,
		rInteger = /^\d+$/,
		mOData2JSOperators = { // mapping of OData operator to JavaScript operator
			And : "&&",
			Eq : "===",
			Ge : ">=",
			Gt : ">",
			Le : "<=",
			Lt : "<",
			Ne : "!==",
			Not : "!",
			Or : "||"
		},
		rSchemaPath = /^(\/dataServices\/schema\/\d+)(?:\/|$)/,
		mType2Category = { // mapping of EDM type to a type category
			"Edm.Boolean" : "boolean",
			"Edm.Byte" : "number",
			"Edm.Date" : "date",
			"Edm.DateTime" : "datetime",
			"Edm.DateTimeOffset" : "datetime",
			"Edm.Decimal" : "decimal",
			"Edm.Double" : "number",
			"Edm.Float" : "number",
			"Edm.Guid" : "string",
			"Edm.Int16" : "number",
			"Edm.Int32" : "number",
			"Edm.Int64" : "decimal",
			"Edm.SByte" : "number",
			"Edm.Single" : "number",
			"Edm.String" : "string",
			"Edm.Time" : "time",
			"Edm.TimeOfDay" : "time"
		},
		mType2Type = { // mapping of constant "edm:*" type to dynamic "Edm.*" type
			Bool : "Edm.Boolean",
			Float : "Edm.Double",
			Date : "Edm.Date",
			DateTimeOffset :"Edm.DateTimeOffset",
			Decimal : "Edm.Decimal",
			Guid : "Edm.Guid",
			Int : "Edm.Int64",
			String : "Edm.String",
			TimeOfDay : "Edm.TimeOfDay"
		},
		mTypeCategoryNeedsCompare = {
			"boolean" : false,
			"date" : true,
			"datetime" : true,
			"decimal" : true,
			"number" : false,
			"string" : false,
			"time" : true
		};

	/**
	 * This object contains helper functions to process an expression in OData V4 annotations.
	 *
	 * The handler functions corresponding to nodes of an annotation expression all use
	 * a parameter oPathValue. This parameter contains the following properties:
	 *

	 *
asExpression: {boolean} parser state: if this property is
	 *    true, an embedded concat must be rendered as an expression
	 *    binding and not a composite binding.
	 *
path: {string} the path in the metamodel that leads to the value
	 *
value: {any} the value of the (sub) expression from the metamodel
	 *
withType: {boolean} parser state: if this property is true,
	 *    all bindings shall have type and constraints information
	 *

	 *
	 * Unless specified otherwise all functions return a result object with the following
	 * properties:
	 *

	 *
result: "binding", "composite", "constant" or "expression"
	 *
value: depending on result:
	 *

	 *
when "binding": {string} the binding path
	 *
when "composite": {string} the binding string incl. the curly braces
	 *
when "constant": {any} the constant value (not escaped if string)
	 *
when "expression": {string} the expression unwrapped (no "{=" and "}")
	 *

	 *
type:  the EDM data type (like "Edm.String") if it could be determined
	 *
constraints: {object} type constraints if result is "binding"
	 *

	 */
	Expression = {
		/**
		 * Adjusts the second operand so that both have the same category, if possible.
		 *
		 * @param {object} oOperand1
		 *   the operand 1 (as a result object with category)
		 * @param {object} oOperand2
		 *   the operand 2 (as a result object with category) - may be modified
		 */
		adjustOperands : function (oOperand1, oOperand2) {
			if (oOperand1.result !== "constant" && oOperand1.category === "number"
					&& oOperand2.result === "constant" && oOperand2.type === "Edm.Int64") {
				// adjust an integer constant of type "Edm.Int64" to the number
				oOperand2.category = "number";
			}
			if (oOperand1.result !== "constant" && oOperand1.category === "decimal"
				&& oOperand2.result === "constant" && oOperand2.type === "Edm.Int32") {
				// adjust an integer constant of type "Edm.Int32" to the decimal
				oOperand2.category = "decimal";
				oOperand2.type = oOperand1.type;
			}
			if (oOperand1.result === "constant" && oOperand1.category === "date"
					&& oOperand2.result !== "constant" && oOperand2.category === "datetime") {
				// adjust a datetime parameter to the date constant
				oOperand2.category = "date";
			}
		},

		/**
		 * Handling of "14.5.3 Expression edm:Apply".
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the apply (see Expression object)
		 * @returns {object}
		 *   the result object
		 */
		apply : function (oInterface, oPathValue) {
			var oName = Basics.descend(oPathValue, "Name", "string"),
				oParameters = Basics.descend(oPathValue, "Parameters");

			switch (oName.value) {
				case "odata.concat": // 14.5.3.1.1 Function odata.concat
					return Expression.concat(oInterface, oParameters);
				case "odata.fillUriTemplate": // 14.5.3.1.2 Function odata.fillUriTemplate
					return Expression.fillUriTemplate(oInterface, oParameters);
				case "odata.uriEncode": // 14.5.3.1.3 Function odata.uriEncode
					return Expression.uriEncode(oInterface, oParameters);
				default:
					Basics.error(oName, "unknown function: " + oName.value);
			}
		},

		/**
		 * Handling of "14.5.3.1.1 Function odata.concat".
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the parameters array (see Expression object)
		 * @returns {object}
		 *   the result object
		 */
		concat : function (oInterface, oPathValue) {
			var bExpression = oPathValue.asExpression,
				aParts = [],
				oResult,
				aResults = [];

			// needed so that we can safely call the forEach
			Basics.expectType(oPathValue, "array");
			oPathValue.value.forEach(function (oUnused, i) {
				// an embedded concat must use expression binding
				oResult = Expression.parameter(oInterface, oPathValue, i);
				// if any parameter is type expression, the concat must become expression, too
				bExpression = bExpression || oResult.result === "expression";
				aResults.push(oResult);
			});
			// convert the results to strings after we know whether the result is expression
			aResults.forEach(function (oResult) {
				if (bExpression) {
					// the expression might have a lower operator precedence than '+'
					Expression.wrapExpression(oResult);
				}
				if (oResult.type !== 'edm:Null') {
					// ignore null (otherwise the string 'null' would appear in expressions)
					aParts.push(Basics.resultToString(oResult, bExpression, oPathValue.withType));
				}
			});
			oResult = bExpression
				? {result : "expression", value : aParts.join("+")}
				: {result : "composite", value : aParts.join("")};
			oResult.type = "Edm.String";
			return oResult;
		},

		/**
		 * Handling of "14.5.6 Expression edm:If".
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the parameters array (see Expression object).
		 *   The first parameter element is the conditional expression and must evaluate to an
		 *   Edm.Boolean. The second and third child elements are the expressions, which are
		 *   evaluated conditionally.
		 * @returns {object}
		 *   the result object
		 */
		conditional : function (oInterface, oPathValue) {
			var oCondition = Expression.parameter(oInterface, oPathValue, 0, "Edm.Boolean"),
				oThen = Expression.parameter(oInterface, oPathValue, 1),
				oElse = Expression.parameter(oInterface, oPathValue, 2),
				sType = oThen.type,
				bWithType = oPathValue.withType;

			if (oThen.type === "edm:Null") {
				sType = oElse.type;
			} else if (oElse.type !== "edm:Null" && oThen.type !== oElse.type) {
				Basics.error(oPathValue,
					"Expected same type for second and third parameter, types are '" + oThen.type
					+ "' and '" + oElse.type + "'");
			}
			return {
				result : "expression",
				type : sType,
				value : Basics.resultToString(Expression.wrapExpression(oCondition), true, false)
					+ "?" + Basics.resultToString(Expression.wrapExpression(oThen), true, bWithType)
					+ ":" + Basics.resultToString(Expression.wrapExpression(oElse), true, bWithType)
			};
		},

		/**
		 * Handling of "14.4 Constant Expressions", i.e.
		 *

		 *
"14.4.2 Expression edm:Bool",

		 *
"14.4.3 Expression edm:Date",

		 *
"14.4.4 Expression edm:DateTimeOffset",

		 *
"14.4.5 Expression edm:Decimal",

		 *
"14.4.8 Expression edm:Float",

		 *
"14.4.9 Expression edm:Guid",

		 *
"14.4.10 Expression edm:Int",

		 *
"14.4.11 Expression edm:String",

		 *
"14.4.12 Expression edm:TimeOfDay".

		 *

		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the constant (see Expression object)
		 * @param {string} sEdmType
		 *   the "edm:*" type of the constant, e.g. "Bool" or "Int"
		 * @returns {object}
		 *   the result object
		 */
		constant : function (oInterface, oPathValue, sEdmType) {
			var sValue = oPathValue.value;

			Basics.expectType(oPathValue, "string");

			if (sEdmType === "String") {
				if (rI18n.test(sValue)) { // a simple binding to "@i18n" model
					return {
						ignoreTypeInPath : true,
						result : "binding",
						type : "Edm.String",
						value : sValue.slice(1, -1) // cut off "{" and "}"
					};
				} else if (oInterface.getSetting && oInterface.getSetting("bindTexts")) {
					// We want a model binding to the path in the metamodel (which is
					// oPathValue.path)
					// "/##" is prepended because it leads from model to metamodel
					return {
						result : "binding",
						type : "Edm.String",
						ignoreTypeInPath : true,
						value : "/##" + Expression.replaceIndexes(oInterface.getModel(),
							oPathValue.path)
					};
				}
				sEdmType = "Edm.String";
			} else if (!mEdmType2RegExp[sEdmType].test(sValue)) {
				Basics.error(oPathValue,
					"Expected " + sEdmType + " value but instead saw '" + sValue + "'");
			} else {
				sEdmType = mType2Type[sEdmType];
				if (sEdmType === "Edm.Int64"
						&& ODataUtils.compare(sValue, sMinSafeInteger, true) >= 0
						&& ODataUtils.compare(sValue, sMaxSafeInteger, true) <= 0) {
					sEdmType = "Edm.Int32";
				}
			}

			return {
				result : "constant",
				type : sEdmType,
				value : sValue
			};
		},

		/**
		 * Calculates an expression.
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the parameters array (see Expression object)
		 * @returns {object}
		 *   the result object
		 */
		expression : function (oInterface, oPathValue) {
			var oRawValue = oPathValue.value,
				oSubPathValue,
				sType;

			Basics.expectType(oPathValue, "object");

			if (oRawValue.hasOwnProperty("Type")) {
				sType = Basics.property(oPathValue, "Type", "string");
				oSubPathValue = Basics.descend(oPathValue, "Value");
			} else {
				["And", "Apply", "Bool", "Date", "DateTimeOffset", "Decimal", "Float", "Eq", "Ge",
					"Gt", "Guid", "If", "Int", "Le", "Lt", "Ne", "Not", "Null", "Or", "Path",
					"PropertyPath", "String", "TimeOfDay"
				].forEach(function (sProperty) {
					if (oRawValue.hasOwnProperty(sProperty)) {
						sType = sProperty;
						oSubPathValue = Basics.descend(oPathValue, sProperty);
					}
				});
			}

			switch (sType) {
				case "Apply": // 14.5.3 Expression edm:Apply
					return Expression.apply(oInterface, oSubPathValue);
				case "If": // 14.5.6 Expression edm:If
					return Expression.conditional(oInterface, oSubPathValue);
				case "Path": // 14.5.12 Expression edm:Path
				case "PropertyPath": // 14.5.13 Expression edm:PropertyPath
					return Expression.path(oInterface, oSubPathValue);
				case "Bool": // 14.4.2 Expression edm:Bool
				case "Date": // 14.4.3 Expression edm:Date
				case "DateTimeOffset": // 14.4.4 Expression edm:DateTimeOffset
				case "Decimal": // 14.4.5 Expression edm:Decimal
				case "Float": // 14.4.8 Expression edm:Float
				case "Guid": // 14.4.9 Expression edm:Guid
				case "Int": // 14.4.10 Expression edm:Int
				case "String": // 14.4.11 Expression edm:String
				case "TimeOfDay": // 14.4.12 Expression edm:TimeOfDay
					return Expression.constant(oInterface, oSubPathValue, sType);
				case "And":
				case "Eq":
				case "Ge":
				case "Gt":
				case "Le":
				case "Lt":
				case "Ne":
				case "Or":
					// 14.5.1 Comparison and Logical Operators
					return Expression.operator(oInterface, oSubPathValue, sType);
				case "Not":
					// 14.5.1 Comparison and Logical Operators
					return Expression.not(oInterface, oSubPathValue);
				case "Null":
					// 14.5.10 Expression edm:Null
					return {
						result : "constant",
						value : "null",
						type : "edm:Null"
					};
				default:
					Basics.error(oPathValue, "Unsupported OData expression");
			}
		},

		/**
		 * Formats the result to be an operand for a logical or comparison operator. Handles
		 * constants accordingly.
		 *
		 * @param {object} oPathValue
		 *   path and value information pointing to the parameters array (for a possible error
		 *   message, see above)
		 * @param {int} iIndex
		 *   the parameter index (for a possible error message)
		 * @param {object} oResult
	 	 *   a result object with category
		 * @param {boolean} bWrapExpression
		 *   if true, wrap an expression in oResult with "()"
		 * @returns {string}
		 *   the formatted result
		 */
		formatOperand : function (oPathValue, iIndex, oResult, bWrapExpression) {
			var oDate;

			if (oResult.result === "constant") {
				switch (oResult.category) {
					case "boolean":
					case "number":
						return oResult.value;
					case "date":
						oDate = Expression.parseDate(oResult.value);
						if (!oDate) {
							Basics.error(Basics.descend(oPathValue, iIndex),
									"Invalid Date " + oResult.value);
						}
						return String(oDate.getTime());
					case "datetime":
						oDate = Expression.parseDateTimeOffset(oResult.value);
						if (!oDate) {
							Basics.error(Basics.descend(oPathValue, iIndex),
									"Invalid DateTime " + oResult.value);
						}
						return String(oDate.getTime());
					case "time":
						return String(Expression.parseTimeOfDay(oResult.value).getTime());
					// no default
				}
			}
			if (bWrapExpression) {
				Expression.wrapExpression(oResult);
			}
			return Basics.resultToString(oResult, true);
		},

		/**
		 * Calculates an expression. Ensures that errors that are thrown via {#error} while
		 * processing are handled accordingly.
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oRawValue
		 *   the raw value from the meta model
		 * @param {boolean} bWithType
		 *   if true, embedded bindings contain type information
		 * @returns {string}
		 *   the expression value or "Unsupported: oRawValue" in case of an error or
		 *   undefined in case the raw value is undefined.
		 */
		getExpression : function (oInterface, oRawValue, bWithType) {
			var oResult;

			if (oRawValue === undefined) {
				return undefined;
			}

			jQuery.sap.measure.average(sPerformanceGetExpression, "", aPerformanceCategories);

			if ( !Expression.simpleParserWarningLogged &&
					ManagedObject.bindingParser === BindingParser.simpleParser) {
				jQuery.sap.log.warning("Complex binding syntax not active", null,
					sAnnotationHelper);
				Expression.simpleParserWarningLogged = true;
			}

			try {
				oResult = Expression.expression(oInterface, {
					asExpression : false,
					path : oInterface.getPath(),
					value : oRawValue,
					withType : bWithType
				});
				jQuery.sap.measure.end(sPerformanceGetExpression);
				return Basics.resultToString(oResult, false, bWithType);
			} catch (e) {
				jQuery.sap.measure.end(sPerformanceGetExpression);
				if (e instanceof SyntaxError) {
					return "Unsupported: "
						+ BindingParser.complexParser.escape(Basics.toErrorString(oRawValue));
				}
				throw e;
			}
		},

		/**
		 * Handling of "14.5.3.1.2 Function odata.fillUriTemplate".
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the parameters array (see Expression object)
		 * @returns {object}
		 *   the result object
		 */
		fillUriTemplate : function (oInterface, oPathValue) {
			var i,
				sName,
				aParts = [],
				sPrefix = "",
				oParameter,
				aParameters = oPathValue.value,
				oResult,
				oTemplate = Expression.parameter(oInterface, oPathValue, 0, "Edm.String");

			aParts.push('odata.fillUriTemplate(', Basics.resultToString(oTemplate, true), ',{');
			for (i = 1; i < aParameters.length; i += 1) {
				oParameter = Basics.descend(oPathValue, i, "object");
				sName = Basics.property(oParameter, "Name", "string");
				oResult = Expression.expression(oInterface, Basics.descend(oParameter, "Value"),
					/*bExpression*/true);
				aParts.push(sPrefix, Basics.toJSON(sName), ":",
					Basics.resultToString(oResult, true));
				sPrefix = ",";
			}
			aParts.push("})");
			return {
				result : "expression",
				value : aParts.join(""),
				type : "Edm.String"
			};
		},

		/**
		 * Handling of "14.5.1 Comparison and Logical Operators": edm:Not.
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the parameter (see Expression object)
		 * @returns {object}
		 *   the result object
		 */
		not : function (oInterface, oPathValue) {
			var oParameter;

			oPathValue.asExpression = true;
			oParameter = Expression.expression(oInterface, oPathValue);
			return {
				result : "expression",
				value : "!" + Basics.resultToString(Expression.wrapExpression(oParameter), true),
				type : "Edm.Boolean"
			};
		},

		/**
		 * Handling of "14.5.1 Comparison and Logical Operators" except edm:Not.
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the parameter array (see Expression object)
		 * @param {string} sType
		 *   the operator as text (like "And" or "Or")
		 * @returns {object}
		 *   the result object
		 */
		operator : function (oInterface, oPathValue, sType) {
			var sExpectedEdmType = sType === "And" || sType === "Or" ? "Edm.Boolean" : undefined,
				oParameter0 = Expression.parameter(oInterface, oPathValue, 0, sExpectedEdmType),
				oParameter1 = Expression.parameter(oInterface, oPathValue, 1, sExpectedEdmType),
				sTypeInfo,
				bNeedsCompare,
				sValue0,
				sValue1;

			if (oParameter0.type !== "edm:Null" && oParameter1.type !== "edm:Null") {
				oParameter0.category = mType2Category[oParameter0.type];
				oParameter1.category = mType2Category[oParameter1.type];
				Expression.adjustOperands(oParameter0, oParameter1);
				Expression.adjustOperands(oParameter1, oParameter0);

				if (oParameter0.category !== oParameter1.category) {
					Basics.error(oPathValue,
						"Expected two comparable parameters but instead saw " + oParameter0.type
						+ " and " + oParameter1.type);
				}
				sTypeInfo = oParameter0.category === "decimal" ? ",true" : "";
				bNeedsCompare = mTypeCategoryNeedsCompare[oParameter0.category];
			}
			sValue0 = Expression.formatOperand(oPathValue, 0, oParameter0, !bNeedsCompare);
			sValue1 = Expression.formatOperand(oPathValue, 1, oParameter1, !bNeedsCompare);
			return {
				result : "expression",
				value : bNeedsCompare
							? "odata.compare(" + sValue0 + "," + sValue1 + sTypeInfo + ")"
								+ mOData2JSOperators[sType] + "0"
							: sValue0 + mOData2JSOperators[sType] + sValue1,
				type : "Edm.Boolean"
			};
		},

		/**
		 * Evaluates a parameter and ensures that the result is of the given EDM type.
		 *
		 * The function calls expression with bExpression=true. This will
		 * cause any embedded odata.concat to generate an expression binding. This
		 * should be correct in any case because only a standalone concat may generate
		 * a composite binding.
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the parameter array (see Expression object)
		 * @param {int} iIndex
		 *   the parameter index
		 * @param {string} [sEdmType]
		 *   the expected EDM type or undefined if any type is allowed
		 * @returns {object}
		 *   the result object
		 */
		parameter : function (oInterface, oPathValue, iIndex, sEdmType) {
			var oParameter = Basics.descend(oPathValue, iIndex),
				oResult;

			oParameter.asExpression = true;
			oResult = Expression.expression(oInterface, oParameter);

			if (sEdmType && sEdmType !== oResult.type) {
				Basics.error(oParameter,
					"Expected " + sEdmType + " but instead saw " + oResult.type);
			}
			return oResult;
		},

		/**
		 * Parses an Edm.Date value and returns the corresponding JavaScript Date value.
		 *
		 * @param {string} sValue
		 *   the Edm.Date value to parse
		 * @returns {Date}
		 *   the JavaScript Date value or null in case the input could not be parsed
		 */
		parseDate : function (sValue) {
			return DateFormat.getDateInstance({
					pattern : "yyyy-MM-dd",
					strictParsing : true,
					UTC : true
				}).parse(sValue);
		},

		/**
		 * Parses an Edm.DateTimeOffset value and returns the corresponding JavaScript Date value.
		 *
		 * @param {string} sValue
		 *   the Edm.DateTimeOffset value to parse
		 * @returns {Date}
		 *   the JavaScript Date value or null in case the input could not be parsed
		 */
		parseDateTimeOffset : function (sValue) {
			var aMatches = mEdmType2RegExp.DateTimeOffset.exec(sValue);
			if (aMatches && aMatches[1] && aMatches[1].length > 4) {
				// "round" to millis, BEWARE of the dot!
				sValue = sValue.replace(aMatches[1], aMatches[1].slice(0, 4));
			}

			return DateFormat.getDateTimeInstance({
				pattern : "yyyy-MM-dd'T'HH:mm:ss.SSSX",
				strictParsing : true
			}).parse(sValue.toUpperCase());
		},

		/**
		 * Parses an Edm.TimeOfDay value and returns the corresponding JavaScript Date value.
		 *
		 * @param {string} sValue
		 *   the Edm.TimeOfDay value to parse
		 * @returns {Date}
		 *   the JavaScript Date value or null in case the input could not be parsed
		 */
		parseTimeOfDay : function (sValue) {
			if (sValue.length > 12) {
				// "round" to millis: "HH:mm:ss.SSS"
				sValue = sValue.slice(0, 12);
			}

			return DateFormat.getTimeInstance({
				pattern : "HH:mm:ss.SSS",
				strictParsing : true,
				UTC : true
			}).parse(sValue);
		},

		/**
		 * Handling of "14.5.12 Expression edm:Path" and "14.5.13 Expression edm:PropertyPath";
		 * embedded within an entity set or entity type (see {@link Basics.followPath}).
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the edm:Path (see Expression object)
		 * @returns {object}
		 *   the result object
		 */
		path : function (oInterface, oPathValue) {
			var sBindingPath = oPathValue.value,
				oConstraints = {},
				oIsDigitSequence,
				oModel = oInterface.getModel(),
				oPathValueInterface = {
					getModel : function () { return oModel; },
					getPath : function () { return oPathValue.path; }
				},
				oProperty,
				oResult = {result : "binding", value : sBindingPath},
				oTarget;

			Basics.expectType(oPathValue, "string");

			// Note: "PropertyPath" is treated the same...
			oTarget = Basics.followPath(oPathValueInterface, {"Path" : sBindingPath});

			if (oTarget && oTarget.resolvedPath) {
				oProperty = oModel.getProperty(oTarget.resolvedPath);
				oResult.type = oProperty.type;
				switch (oProperty.type) {
				case "Edm.DateTime":
					oConstraints.displayFormat = oProperty["sap:display-format"];
					break;
				case "Edm.Decimal":
					oConstraints.precision = oProperty.precision;
					oConstraints.scale = oProperty.scale;
					break;
				case "Edm.String":
					oConstraints.maxLength = oProperty.maxLength;
					oIsDigitSequence = oProperty["com.sap.vocabularies.Common.v1.IsDigitSequence"];
					if (oIsDigitSequence) {
						oConstraints.isDigitSequence = oIsDigitSequence.Bool;
					}
					break;
				// no default
				}
				if (oProperty.nullable === "false") {
					oConstraints.nullable = oProperty.nullable;
				}
				oResult.constraints = oConstraints;
			} else {
				jQuery.sap.log.warning("Could not find property '" + sBindingPath
					+ "' starting from '" + oPathValue.path + "'", null, sAnnotationHelper);
			}

			return oResult;
		},

		/**
		 * Replaces the indexes in the given path by queries in the form
		 * [${key}==='value'] if possible. Expects the path to start with
		 * "/dataServices/schema//".
		 *
		 * @param {sap.ui.model.Model} oModel
		 *   the model the path belongs to
		 * @param {string} sPath
		 *   the path, where to replace the indexes
		 * @returns {string}
		 *   the replaced path
		 */
		replaceIndexes : function (oModel, sPath) {
			var aMatches,
				aParts = sPath.split('/'),
				sObjectPath,
				sRecordType;

			/**
			 * Processes the property with the given path of the object at sObjectPath.
			 * If it exists and is of type "string", the index at position i in
			 * aParts is replaced by a query "[${propertyPath}==='propertyValue']".
			 *
			 * @param {string} sPropertyPath the property path
			 * @param {number} i the index in aParts
			 * @returns {boolean} true if the index was replaced by a query
			 */
			function processProperty(sPropertyPath, i) {
				var sProperty = oModel.getProperty(sObjectPath + "/" + sPropertyPath);

				if (typeof sProperty === "string") {
					aParts[i] = "[${" + sPropertyPath + "}===" + Basics.toJSON(sProperty) + "]";
					return true;
				}
				return false;
			}

			aMatches = rSchemaPath.exec(sPath);
			if (!aMatches) {
				return sPath;
			}
			sObjectPath = aMatches[1];
			// aParts now contains ["", "dataServices", "schema", "", ...]
			// try to replace the schema index in aParts[3] by a query for the schema's namespace
			if (!processProperty("namespace", 3)) {
				return sPath;
			}
			// continue after the schema index
			for (var i = 4; i < aParts.length; i++) {
				sObjectPath = sObjectPath + "/" + aParts[i];
				// if there is an index, first try a query for "name"
				if (rInteger.test(aParts[i]) && !processProperty("name", i)) {
					// check data fields: since they always extend DataFieldAbstract, the record
					// type must be given
					sRecordType = oModel.getProperty(sObjectPath + "/RecordType");
					if (sRecordType) {
						if (sRecordType === "com.sap.vocabularies.UI.v1.DataFieldForAction") {
							processProperty("Action/String", i);
						} else if (sRecordType ===
								"com.sap.vocabularies.UI.v1.DataFieldForAnnotation") {
							processProperty("Target/AnnotationPath", i);
						} else if (sRecordType.indexOf("com.sap.vocabularies.UI.v1.DataField")
								=== 0) {
							processProperty("Value/Path", i);
						}
					}
				}
			}
			return aParts.join('/');
		},

		/**
		 * Flag indicating that warning for missing complex binding parser has already been logged.
		 *
		 * @type {boolean}
		*/
		simpleParserWarningLogged : false,

		/**
		 * Handling of "14.5.3.1.3 Function odata.uriEncode".
		 *
		 * @param {sap.ui.core.util.XMLPreprocessor.IContext|sap.ui.model.Context} oInterface
		 *   the callback interface related to the current formatter call
		 * @param {object} oPathValue
		 *   path and value information pointing to the parameters array (see Expression object)
		 * @returns {object}
		 *   the result object
		 */
		uriEncode : function (oInterface, oPathValue) {
			var oResult = Expression.parameter(oInterface, oPathValue, 0);

			if (oResult.result === "constant") {
				// convert V4 to V2 for sap.ui.model.odata.ODataUtils
				if (oResult.type === "Edm.Date") {
					oResult.type = "Edm.DateTime";
					// Note: ODataUtils.formatValue calls Date.parse() indirectly, use UTC to make
					// sure IE9 does not mess with time zone
					oResult.value = oResult.value + "T00:00:00Z";
				} else if (oResult.type === "Edm.TimeOfDay") {
					oResult.type = "Edm.Time";
					oResult.value = "PT"
						+ oResult.value.slice(0, 2) + "H"
						+ oResult.value.slice(3, 5) + "M"
						+ oResult.value.slice(6, 8) + "S";
				}
			}

			return {
				result : "expression",
				value : 'odata.uriEncode(' + Basics.resultToString(oResult, true) + ","
					+ Basics.toJSON(oResult.type) + ")",
				type : "Edm.String"
			};
		},

		/**
		 * Wraps the result's value with "()" in case it is an expression because the result will be
		 * become a parameter of an infix operator and we have to ensure that the operator precedence
		 * remains correct.
		 *
		 * @param {object} oResult
		 *   a result object
		 * @returns {object}
		 *   the given result object (for chaining)
		 */
		wrapExpression : function (oResult) {
			if (oResult.result === "expression") {
				oResult.value = "(" + oResult.value + ")";
			}
			return oResult;
		}
	};

	return Expression;

}, /* bExport= */ false);


text:
"""Loader for the Labeled Faces in the Wild (LFW) dataset

This dataset is a collection of JPEG pictures of famous people collected
over the internet, all details are available on the official website:

    http://vis-www.cs.umass.edu/lfw/

Each picture is centered on a single face. The typical task is called
Face Verification: given a pair of two pictures, a binary classifier
must predict whether the two images are from the same person.

An alternative task, Face Recognition or Face Identification is:
given the picture of the face of an unknown person, identify the name
of the person by refering to a gallery of previously seen pictures of
identified persons.

Both Face Verification and Face Recognition are tasks that are typically
performed on the output of a model trained to perform Face Detection. The
most popular model for Face Detection is called Viola-Johns and is
implemented in the OpenCV library. The LFW faces were extracted by this face
detector from various online websites.
"""
# Copyright (c) 2011 Olivier Grisel <olivier.grisel@ensta.org>
# License: Simplified BSD

from os import listdir, makedirs, remove
from os.path import join, exists, isdir

import logging
import numpy as np
import urllib

from .base import get_data_home, Bunch
from ..externals.joblib import Memory

from ..externals.six import b, u

logger = logging.getLogger(__name__)

BASE_URL = "http://vis-www.cs.umass.edu/lfw/"
ARCHIVE_NAME = "lfw.tgz"
FUNNELED_ARCHIVE_NAME = "lfw-funneled.tgz"
TARGET_FILENAMES = [
    'pairsDevTrain.txt',
    'pairsDevTest.txt',
    'pairs.txt',
]

def scale_face(face):
    """Scale back to 0-1 range in case of normalization for plotting"""
    scaled = face - face.min()
    scaled /= scaled.max()
    return scaled

#
# Common private utilities for data fetching from the original LFW website
# local disk caching, and image decoding.
#

def check_fetch_lfw(data_home=None, funneled=True, download_if_missing=True):
    """Helper function to download any missing LFW data"""
    data_home = get_data_home(data_home=data_home)
    lfw_home = join(data_home, "lfw_home")

    if funneled:
        archive_path = join(lfw_home, FUNNELED_ARCHIVE_NAME)
        data_folder_path = join(lfw_home, "lfw_funneled")
        archive_url = BASE_URL + FUNNELED_ARCHIVE_NAME
    else:
        archive_path = join(lfw_home, ARCHIVE_NAME)
        data_folder_path = join(lfw_home, "lfw")
        archive_url = BASE_URL + ARCHIVE_NAME

    if not exists(lfw_home):
        makedirs(lfw_home)

    for target_filename in TARGET_FILENAMES:
        target_filepath = join(lfw_home, target_filename)
        if not exists(target_filepath):
            if download_if_missing:
                url = BASE_URL + target_filename
                logger.warn("Downloading LFW metadata: %s", url)
                urllib.urlretrieve(url, target_filepath)
            else:
                raise IOError("%s is missing" % target_filepath)

    if not exists(data_folder_path):

        if not exists(archive_path):
            if download_if_missing:
                logger.warn("Downloading LFW data (~200MB): %s", archive_url)
                urllib.urlretrieve(archive_url, archive_path)
            else:
                raise IOError("%s is missing" % target_filepath)

        import tarfile
        logger.info("Decompressing the data archive to %s", data_folder_path)
        tarfile.open(archive_path, "r:gz").extractall(path=lfw_home)
        remove(archive_path)

    return lfw_home, data_folder_path

def _load_imgs(file_paths, slice_, color, resize):
    """Internally used to load images"""

    # Try to import imread and imresize from PIL. We do this here to prevent
    # the whole sklearn.datasets module from depending on PIL.
    try:
        try:
            from scipy.misc import imread
        except ImportError:
            from scipy.misc.pilutil import imread
        from scipy.misc import imresize
    except ImportError:
        raise ImportError("The Python Imaging Library (PIL)"
                          "is required to load data from jpeg files")

    # compute the portion of the images to load to respect the slice_ parameter
    # given by the caller
    default_slice = (slice(0, 250), slice(0, 250))
    if slice_ is None:
        slice_ = default_slice
    else:
        slice_ = tuple(s or ds for s, ds in zip(slice_, default_slice))

    h_slice, w_slice = slice_
    h = (h_slice.stop - h_slice.start) / (h_slice.step or 1)
    w = (w_slice.stop - w_slice.start) / (w_slice.step or 1)

    if resize is not None:
        resize = float(resize)
        h = int(resize * h)
        w = int(resize * w)

    # allocate some contiguous memory to host the decoded image slices
    n_faces = len(file_paths)
    if not color:
        faces = np.zeros((n_faces, h, w), dtype=np.float32)
    else:
        faces = np.zeros((n_faces, h, w, 3), dtype=np.float32)

    # iterate over the collected file path to load the jpeg files as numpy
    # arrays
    for i, file_path in enumerate(file_paths):
        if i % 1000 == 0:
            logger.info("Loading face #%05d / %05d", i + 1, n_faces)
        face = np.asarray(imread(file_path)[slice_], dtype=np.float32)
        face /= 255.0  # scale uint8 coded colors to the [0.0, 1.0] floats
        if resize is not None:
            face = imresize(face, resize)
        if not color:
            # average the color channels to compute a gray levels
            # representaion
            face = face.mean(axis=2)

        faces[i, ...] = face

    return faces

#
# Task #1:  Face Identification on picture with names
#

def _fetch_lfw_people(data_folder_path, slice_=None, color=False, resize=None,
                      min_faces_per_person=0):
    """Perform the actual data loading for the lfw people dataset

    This operation is meant to be cached by a joblib wrapper.
    """
    # scan the data folder content to retain people with more that
    # `min_faces_per_person` face pictures
    person_names, file_paths = [], []
    for person_name in sorted(listdir(data_folder_path)):
        folder_path = join(data_folder_path, person_name)
        if not isdir(folder_path):
            continue
        paths = [join(folder_path, f) for f in listdir(folder_path)]
        n_pictures = len(paths)
        if n_pictures >= min_faces_per_person:
            person_name = person_name.replace('_', ' ')
            person_names.extend([person_name] * n_pictures)
            file_paths.extend(paths)

    n_faces = len(file_paths)
    if n_faces == 0:
        raise ValueError("min_faces_per_person=%d is too restrictive" %
                         min_faces_per_person)

    target_names = np.unique(person_names)
    target = np.searchsorted(target_names, person_names)

    faces = _load_imgs(file_paths, slice_, color, resize)

    # shuffle the faces with a deterministic RNG scheme to avoid having
    # all faces of the same person in a row, as it would break some
    # cross validation and learning algorithms such as SGD and online
    # k-means that make an IID assumption

    indices = np.arange(n_faces)
    np.random.RandomState(42).shuffle(indices)
    faces, target = faces[indices], target[indices]
    return faces, target, target_names

def fetch_lfw_people(data_home=None, funneled=True, resize=0.5,
                     min_faces_per_person=0, color=False,
                     slice_=(slice(70, 195), slice(78, 172)),
                     download_if_missing=True):
    """Loader for the Labeled Faces in the Wild (LFW) people dataset

    This dataset is a collection of JPEG pictures of famous people
    collected on the internet, all details are available on the
    official website:

        http://vis-www.cs.umass.edu/lfw/

    Each picture is centered on a single face. Each pixel of each channel
    (color in RGB) is encoded by a float in range 0.0 - 1.0.

    The task is called Face Recognition (or Identification): given the
    picture of a face, find the name of the person given a training set
    (gallery).

    Parameters
    ----------
    data_home: optional, default: None
        Specify another download and cache folder for the datasets. By default
        all scikit learn data is stored in '~/scikit_learn_data' subfolders.

    funneled: boolean, optional, default: True
        Download and use the funneled variant of the dataset.

    resize: float, optional, default 0.5
        Ratio used to resize the each face picture.

    min_faces_per_person: int, optional, default None
        The extracted dataset will only retain pictures of people that have at
        least `min_faces_per_person` different pictures.

    color: boolean, optional, default False
        Keep the 3 RGB channels instead of averaging them to a single
        gray level channel. If color is True the shape of the data has
        one more dimension than than the shape with color = False.

    slice_: optional
        Provide a custom 2D slice (height, width) to extract the
        'interesting' part of the jpeg files and avoid use statistical
        correlation from the background

    download_if_missing: optional, True by default
        If False, raise a IOError if the data is not locally available
        instead of trying to download the data from the source site.
    """
    lfw_home, data_folder_path = check_fetch_lfw(
        data_home=data_home, funneled=funneled,
        download_if_missing=download_if_missing)
    logger.info('Loading LFW people faces from %s', lfw_home)

    # wrap the loader in a memoizing function that will return memmaped data
    # arrays for optimal memory usage
    m = Memory(cachedir=lfw_home, compress=6, verbose=0)
    load_func = m.cache(_fetch_lfw_people)

    # load and memoize the pairs as np arrays
    faces, target, target_names = load_func(
        data_folder_path, resize=resize,
        min_faces_per_person=min_faces_per_person, color=color, slice_=slice_)

    # pack the results as a Bunch instance
    return Bunch(data=faces.reshape(len(faces), -1), images=faces,
                 target=target, target_names=target_names,
                 DESCR="LFW faces dataset")

#
# Task #2:  Face Verification on pairs of face pictures
#

def _fetch_lfw_pairs(index_file_path, data_folder_path, slice_=None,
                     color=False, resize=None):
    """Perform the actual data loading for the LFW pairs dataset

    This operation is meant to be cached by a joblib wrapper.
    """
    # parse the index file to find the number of pairs to be able to allocate
    # the right amount of memory before starting to decode the jpeg files
    with open(index_file_path, 'rb') as index_file:
        split_lines = [ln.strip().split(b('\t')) for ln in index_file]
    pair_specs = [sl for sl in split_lines if len(sl) > 2]
    n_pairs = len(pair_specs)

    # interating over the metadata lines for each pair to find the filename to
    # decode and load in memory
    target = np.zeros(n_pairs, dtype=np.int)
    file_paths = list()
    for i, components in enumerate(pair_specs):
        if len(components) == 3:
            target[i] = 1
            pair = (
                (components[0], int(components[1]) - 1),
                (components[0], int(components[2]) - 1),
            )
        elif len(components) == 4:
            target[i] = 0
            pair = (
                (components[0], int(components[1]) - 1),
                (components[2], int(components[3]) - 1),
            )
        else:
            raise ValueError("invalid line %d: %r" % (i + 1, components))
        for j, (name, idx) in enumerate(pair):
            try:
                person_folder = join(data_folder_path, name)
            except TypeError:
                person_folder = join(data_folder_path, str(name, 'UTF-8'))
            filenames = list(sorted(listdir(person_folder)))
            file_path = join(person_folder, filenames[idx])
            file_paths.append(file_path)

    pairs = _load_imgs(file_paths, slice_, color, resize)
    shape = list(pairs.shape)
    n_faces = shape.pop(0)
    shape.insert(0, 2)
    shape.insert(0, n_faces // 2)
    pairs.shape = shape

    return pairs, target, np.array(['Different persons', 'Same person'])

def load_lfw_people(download_if_missing=False, **kwargs):
    """Alias for fetch_lfw_people(download_if_missing=False)

    Check fetch_lfw_people.__doc__ for the documentation and parameter list.
    """
    return fetch_lfw_people(download_if_missing=download_if_missing, **kwargs)

def fetch_lfw_pairs(subset='train', data_home=None, funneled=True, resize=0.5,
                    color=False, slice_=(slice(70, 195), slice(78, 172)),
                    download_if_missing=True):
    """Loader for the Labeled Faces in the Wild (LFW) pairs dataset

    This dataset is a collection of JPEG pictures of famous people
    collected on the internet, all details are available on the
    official website:

        http://vis-www.cs.umass.edu/lfw/

    Each picture is centered on a single face. Each pixel of each channel
    (color in RGB) is encoded by a float in range 0.0 - 1.0.

    The task is called Face Verification: given a pair of two pictures,
    a binary classifier must predict whether the two images are from
    the same person.

    In the official `README.txt`_ this task is described as the
    "Restricted" task.  As I am not sure as to implement the
    "Unrestricted" variant correctly, I left it as unsupported for now.

      .. _`README.txt`: http://vis-www.cs.umass.edu/lfw/README.txt

    Parameters
    ----------
    subset: optional, default: 'train'
        Select the dataset to load: 'train' for the development training
        set, 'test' for the development test set, and '10_folds' for the
        official evaluation set that is meant to be used with a 10-folds
        cross validation.

    data_home: optional, default: None
        Specify another download and cache folder for the datasets. By
        default all scikit learn data is stored in '~/scikit_learn_data'
        subfolders.

    funneled: boolean, optional, default: True
        Download and use the funneled variant of the dataset.

    resize: float, optional, default 0.5
        Ratio used to resize the each face picture.

    color: boolean, optional, default False
        Keep the 3 RGB channels instead of averaging them to a single
        gray level channel. If color is True the shape of the data has
        one more dimension than than the shape with color = False.

    slice_: optional
        Provide a custom 2D slice (height, width) to extract the
        'interesting' part of the jpeg files and avoid use statistical
        correlation from the background

    download_if_missing: optional, True by default
        If False, raise a IOError if the data is not locally available
        instead of trying to download the data from the source site.
    """
    lfw_home, data_folder_path = check_fetch_lfw(
        data_home=data_home, funneled=funneled,
        download_if_missing=download_if_missing)
    logger.info('Loading %s LFW pairs from %s', subset, lfw_home)

    # wrap the loader in a memoizing function that will return memmaped data
    # arrays for optimal memory usage
    m = Memory(cachedir=lfw_home, compress=6, verbose=0)
    load_func = m.cache(_fetch_lfw_pairs)

    # select the right metadata file according to the requested subset
    label_filenames = {
        'train': 'pairsDevTrain.txt',
        'test': 'pairsDevTest.txt',
        '10_folds': 'pairs.txt',
    }
    if subset not in label_filenames:
        raise ValueError("subset='%s' is invalid: should be one of %r" % (
            subset, list(sorted(label_filenames.keys()))))
    index_file_path = join(lfw_home, label_filenames[subset])

    # load and memoize the pairs as np arrays
    pairs, target, target_names = load_func(
        index_file_path, data_folder_path, resize=resize, color=color,
        slice_=slice_)

    # pack the results as a Bunch instance
    return Bunch(data=pairs.reshape(len(pairs), -1), pairs=pairs,
                 target=target, target_names=target_names,
                 DESCR="'%s' segment of the LFW pairs dataset" % subset)

def load_lfw_pairs(download_if_missing=False, **kwargs):
    """Alias for fetch_lfw_pairs(download_if_missing=False)

    Check fetch_lfw_pairs.__doc__ for the documentation and parameter list.
    """
    return fetch_lfw_pairs(download_if_missing=download_if_missing, **kwargs)


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">android-fragments-using-java</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="fragtransaction">my_fragment</string>

</resources>


text:
//// [declarationEmitClassMemberNameConflict2.ts]
const Bar = 'bar';

enum Hello {
    World
}

enum Hello1 {
    World1
}

class Foo {
    // Same names + string => OK
    Bar = Bar;

    // Same names + enum => OK
    Hello = Hello;

    // Different names + enum => OK
    Hello2 = Hello1;
}

//// [declarationEmitClassMemberNameConflict2.js]
var Bar = 'bar';
var Hello;
(function (Hello) {
    Hello[Hello["World"] = 0] = "World";
})(Hello || (Hello = {}));
var Hello1;
(function (Hello1) {
    Hello1[Hello1["World1"] = 0] = "World1";
})(Hello1 || (Hello1 = {}));
var Foo = /** @class */ (function () {
    function Foo() {
        // Same names + string => OK
        this.Bar = Bar;
        // Same names + enum => OK
        this.Hello = Hello;
        // Different names + enum => OK
        this.Hello2 = Hello1;
    }
    return Foo;
}());

//// [declarationEmitClassMemberNameConflict2.d.ts]
declare const Bar = "bar";
declare enum Hello {
    World = 0,
}
declare enum Hello1 {
    World1 = 0,
}
declare class Foo {
    Bar: string;
    Hello: typeof Hello;
    Hello2: typeof Hello1;
}


text:
luoo-down
=========

luoo-down is a [luoo.net-落网](http://www.luoo.net/) music downloader based on nodejs.

This is a simple of fetching <http://www.luoo.net/music/613>

![luoo-down](http://stanzhai.github.io/images/project/luoo-down.png)

## How to use

1. Use git clone this code `git clone https://github.com/stanzhai/luoo-down.git`
2. Run `npm install` then run luoo-down by command `node app`
3. Select the music you want to download then press ENTER.
4. After the music has been downloaded, press ENTER open the music in you preferred application !
5. The downloaded music path is `downloads`, under this folder you will see:

  ![download path](http://stanzhai.github.io/images/project/luoo-down-path.png)

## License

The MIT License (MIT)


text:
import reveal
import subscribe

import utils
import model
from google.appengine.ext import db

from django.utils.translation import ugettext as _

class ConfirmPostNoteWithBadWordsError(Exception):
    """Container for user-facing error messages when confirming to post
    a note with bad words."""
    pass

class Handler(utils.BaseHandler):
    """This handler lets the author confirm to post a note containing
    bad words."""

    def get(self):
        try:
            note, token = self.get_note_and_verify_params()
        except ConfirmPostNoteWithBadWordsError, e:
            return self.error(400, unicode(e))

        self.confirm_note_with_bad_words(note)
        record_url = self.get_url(
            '/view', id=note.person_record_id, repo=note.repo)

        self.redirect(record_url)

    def post(self):
        try:
            note, token = self.get_note_and_verify_params()
        except ConfirmPostNoteWithBadWordsError, e:
            return self.error(400, unicode(e))

        self.confirm_note_with_bad_words(note)
        record_url = self.get_url(
            '/view', id=note.person_record_id, repo=note.repo)

        self.redirect(record_url)

    def get_note_and_verify_params(self):
        """Check the request for a valid note record_id and valid crypto token.
        Returns a tuple containing: (note, token)
        If there is an error we raise a ConfirmPostNoteWithBadWordsError. """
        keyname = "%s:%s" % (self.repo, self.params.id)
        note = model.NoteWithBadWords.get_by_key_name(keyname)
        if not note:
            # Place holder name here is id_str, not id, because
            # the translation system doesn't allow the same string in both
            # a place holder name and a normal uppercase word in one message.
            raise ConfirmPostNoteWithBadWordsError(
                _('No note with ID: %(id_str)s.') % {'id_str': keyname})

        token = self.request.get('token')
        data = 'confirm_post_note_with_bad_words:%s' % self.params.id
        if not reveal.verify(data, token):
            raise ConfirmPostNoteWithBadWordsError(
                _("The token %(token)s was invalid.") % {'token': token})

        return (note, token)

    def confirm_note_with_bad_words(self, note):
        """After a note containing bad words is confirmed by the author,
        we will:
        (1) set note.confirmed = True;
        (2) copy the note from NoteWithBadWords to Note;
        (3) log user action;
        (4) update person record. """
        note.confirmed = True;

        # Check whether the record author disabled notes on
        # this record during the time between the note author inputs the
        # note in the UI and confirms the note through email.
        person = model.Person.get(self.repo, note.person_record_id)
        if person.notes_disabled:
            return self.error(
                200, _('The author has disabled notes on this record.'))

        # Check whether the admin disabled reporting "believed_dead"
        # during the time between the note author inputs the
        # note in the UI and confirms the note through email.
        if (self.params.status == 'believed_dead' and
            not self.config.allow_believed_dead_via_ui):
            return self.error(
                200, _('Not authorized to post notes with the status '
                       '"believed_dead".'))

        # clone the flagged note to Note table.
        note_confirmed = model.Note.create_original(
            self.repo,
            entry_date=note.entry_date,
            person_record_id=note.person_record_id,
            author_name=note.author_name,
            author_email=note.author_email,
            author_phone=note.author_phone,
            source_date=note.source_date,
            author_made_contact=note.author_made_contact,
            status=note.status,
            email_of_found_person=note.email_of_found_person,
            phone_of_found_person=note.phone_of_found_person,
            last_known_location=note.last_known_location,
            text=note.text)
        entities_to_put = [note_confirmed]

        note.confirmed_copy_id = note_confirmed.get_record_id()
        entities_to_put.append(note)

        # Specially log 'believed_dead'.
        if note_confirmed.status == 'believed_dead':
            model.UserActionLog.put_new(
                    'mark_dead', note_confirmed, person.primary_full_name,
                    self.request.remote_addr)

        # Specially log a switch to an alive status.
        if (note_confirmed.status in ['believed_alive', 'is_note_author'] and
            person.latest_status not in ['believed_alive', 'is_note_author']):
            model.UserActionLog.put_new(
                    'mark_alive', note_confirmed, person.primary_full_name)

        # Update the Person based on the Note.
        if person:
            person.update_from_note(note_confirmed)
            # Send notification to all people
            # who subscribed to updates on this person
            subscribe.send_notifications(self, person, [note_confirmed])
            entities_to_put.append(person)

        # Write one or both entities to the store.
        db.put(entities_to_put)


text:
require "log4r"

module VagrantPlugins
  module Fifo
    module Action
      # This terminates the running instance.
      class TerminateInstance
        def initialize(app, env)
          @app    = app
          @logger = Log4r::Logger.new("vagrant_fifo::action::run_instance")
        end

        def call(env)
          server = env[:fifo_compute].vms.get(env[:machine].id)

          # Destroy the server and remove the tracking ID
          env[:ui].info(I18n.t("vagrant_fifo.terminating"))

          # Machine must be in a stopped state before it's destroyed.
          #
          # More info here:
          #
          #   https://us-west-1.api.fifocloud.com/docs#DeleteMachine
          #
          env[:fifo_compute].vms.delete(server['uuid'])

          # Wait for server to be completely gone from invetory
          while true do
            ids = env[:fifo_compute].vms.list

            unless ids.include?(env[:machine].id) then
              break
            end
            sleep 5
          end

          env[:machine].id = nil

          @app.call(env)
        end
      end
    end
  end
end


text:
const request = require('supertest');
let expect = require('chai').expect;
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const PORT = process.env.PORT || 5000;
const MONGO_URI = process.env.MONGO_URI;

const TEST_USER_ID = 'TEST12345';

const Bots = require('../../dist/api/bots');

function createServer() {
    let app = express();
    app.use(bodyParser.json());
    app.use('/api/bots', Bots);
    return app.listen(PORT);
}

// Original data to POST
let testBot = {
    userId: TEST_USER_ID,
    botname: 'Test Bot',
    index: 0
};

// Request body to update with PUT
const update = {
    index: 1,
    botname: 'Updated Test Bot',
    postAsSlackbot: false
};

let server;

before(() => {
    mongoose.connect(MONGO_URI);
    mongoose.model('Bot').remove({ userId: TEST_USER_ID }).exec();
});

after(() => mongoose.connection.close());

describe('/api/bots', () => {

    beforeEach(() => server = createServer());

    afterEach(done => server.close(done));

    describe('POST', () => {
        it('creates a new bot', done => {
            request(server)
                .post('/api/bots')
                .send(testBot)
                .expect(200)
                .end((err, res) => {
                    if (err) { return done(err); }
                    expect(res.body._id).to.be.defined;
                    expect(res.body.userId).to.equal(testBot.userId);
                    expect(res.body.botname).to.equal(testBot.botname);
                    expect(res.body.index).to.equal(testBot.index);

                    testBot = res.body;

                    done();
                });
        });

        Object.keys(testBot).forEach(k => {
            let _body = JSON.parse(JSON.stringify(testBot)); // clone object
            delete _body[k];
            it(`returns a 400 with missing required parameter: ${k}`, done => {
                request(server)
                    .post('/api/bots')
                    .send(_body)
                    .expect(400, done);
            });
        });
    });

    describe('GET', () => {
        it('retrieves newly created bot', done => {
            request(server)
                .get(`/api/bots?userId=${TEST_USER_ID}`)
                .expect(200)
                .end((err, res) => {
                    if (err) { return done(err); }
                    expect(res.body).to.have.lengthOf(1);
                    expect(res.body[0]).to.deep.equal(testBot);
                    done();
                });
        });

        it('returns a 400 with missing required parameter: userId', done => {
            request(server)
                .get('/api/bots')
                .expect(400, done);
        });
    });

});

describe('/api/bots/:id', () => {

    beforeEach(() => server = createServer());

    afterEach(done => server.close(done));

    describe('PUT', () => {
        it('updates the bot', done => {
            request(server)
                .put(`/api/bots/${testBot._id}`)
                .send(update)
                .expect(200)
                .end((err, res) => {
                    if (err) { return done(err); }
                    expect(res.body.index).to.equal(update.index);
                    expect(res.body.botname).to.equal(update.botname);
                    expect(res.body.postAsSlackbot).to.equal(update.postAsSlackbot);
                    done();
                });
        });
    });

    describe('GET', () => {
        it('correctly retrieves updated bot', done => {
            request(server)
                .get(`/api/bots/${testBot._id}`)
                .expect(200)
                .end((err, res) => {
                    if (err) { return done(err); }
                    expect(res.body.index).to.equal(update.index);
                    expect(res.body.botname).to.equal(update.botname);
                    expect(res.body.postAsSlackbot).to.equal(update.postAsSlackbot);
                    done();
                });
        });
    });

    describe('DELETE', () => {
        it('deletes the bot', done => {
            request(server)
                .delete(`/api/bots/${testBot._id}`)
                .expect(200)
                .end(() => {
                    request(server)
                        .get(`/api/bots/${testBot._id}`)
                        .expect(404, done);
                });
        });
    });
});

describe('/api/bots/:id/send', () => {

    beforeEach(() => server = createServer());

    afterEach(done => server.close(done));

    describe('POST', () => {
        let body = { token: 'blah', channel: 'U12345', message: 'Test' };

        it('returns a 401 with an invalid token', done => {
            request(server)
                .post(`/api/bots/${testBot._id}/send`)
                .send(body)
                .expect(401, done);
        });

        Object.keys(body).forEach(k => {
            let _body = JSON.parse(JSON.stringify(body)); // clone object
            delete _body[k];
            it(`returns a 400 with missing required parameter: ${k}`, done => {
                request(server)
                    .post('/api/bots')
                    .send(_body)
                    .expect(400, done);
            });
        });
    })
})


text:
<?php requireLib('flot') ?>
<?php echoUOJPageHeader('关于我') ?>
<?php uojIncludeView('user-info', ['user' => UOJUserBlog::user()]); ?>
<?php echoUOJPageFooter() ?>


text:
/**
 * Generates a random UUID string.
 */
export function randomUuid(): string {
    // TODO: Support cases where crypto.getRandomValues is not supported.
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
        let r = crypto.getRandomValues(new Uint8Array(1))[0] % 16 | 0;
        let v = c === 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}


text:
package com.compomics.sigpep.model;

/**
 * A splice event is defined by an upstream and downstream exon.
 *

 * Created by IntelliJ IDEA.

 * User: mmueller

 * Date: 01-Feb-2008

 * Time: 15:29:42

 */
public interface SpliceEvent {

    /**
     * Returns the upstream exon defining the splice event.
     *
     * @return the exon
     */
    Exon getUpstreamExon();

    /**
     * Sets the upsteam exon defining the splice event.
     *
     * @param exon the exon
     */
    void setUpstreamExon(Exon exon);

    /**
     * Returns the upstream exon defining the splice event.
     *
     * @return the exon
     */
    Exon getDownstreamExon();

    /**
     * Sets the upsteam exon defining the splice event.
     *
     * @param exon the exon
     */
    void setDownstreamExon(Exon exon);
}


text:
package com.hmsonline.cassandra.triggers.dao;

import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

import org.apache.cassandra.db.ColumnFamily;
import org.apache.cassandra.db.RowMutation;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hmsonline.cassandra.triggers.LogEntry;
import com.hmsonline.cassandra.triggers.Trigger;
import com.hmsonline.cassandra.triggers.TriggerTask;

public class CommitLog extends LogEntryStore {
    private static Logger logger = LoggerFactory.getLogger(CommitLog.class);

    public static final String KEYSPACE = "triggers";
    public static final String COLUMN_FAMILY_PREFIX = "CommitLog";
    public static final int MAX_NUMBER_COLUMNS = 100;
    public static final int BATCH_SIZE = 1000;
    private static final int PENDING_PRIORITY = 1;
    private Thread triggerThread = null;
    private static final long MAX_LOG_ENTRY_AGE = 5000; // age of entry, at
                                                        // which time any node
                                                        // can process it.
    public CommitLog() throws Exception {
        super(KEYSPACE, COLUMN_FAMILY_PREFIX);
        logger.warn("Instantiated commit log [" + this.getColumnFamily() + "]");
        triggerThread = new Thread(new TriggerTask());
        triggerThread.start();
        logger.debug("Started Trigger Task thread.");
    }

    private static CommitLog instance = null;

    public static synchronized CommitLog getCommitLog() throws Exception {
        if (instance == null) {
            instance = new CommitLog();
        }
        return instance;
    }

    public List<LogEntry> writePending(ConsistencyLevel consistencyLevel, RowMutation rowMutation) throws Throwable {
        List<String> columnNames = new ArrayList<String>();
        for (ColumnFamily cf : rowMutation.getColumnFamilies()) {
            for (ByteBuffer b : cf.getColumnNames()) {
                columnNames.add(ByteBufferUtil.string(b));
            }
        }
        String keyspace = rowMutation.getTable();
        ByteBuffer rowKey = rowMutation.key();
        List<LogEntry> entries = new ArrayList<LogEntry>();
        for (Integer cfId : rowMutation.getColumnFamilyIds()) {
            ColumnFamily columnFamily = rowMutation.getColumnFamily(cfId);
            String path = keyspace + ":" + columnFamily.metadata().cfName;
            List<Trigger> triggers = TriggerStore.getStore().getTriggers().get(path);
            if (triggers != null && triggers.size() > 0) {
                String hostName = LogEntryStore.getHostName();
                LogEntry entry = new LogEntry(keyspace, columnFamily, rowKey, consistencyLevel, hostName,
                        System.currentTimeMillis(), columnNames);
                entries.add(entry);
                write(entry, PENDING_PRIORITY);
            }
        }
        return entries;
    }

    public List<LogEntry> getPending() throws Throwable {
        /*
         * Should revisit this perhaps.
         */
        String thisHoursKey = CommitLog.getKey();
        String previousHoursKey = CommitLog.getPreviousKey();
        List<LogEntry> result = new ArrayList<LogEntry>();
        SlicePredicate predicate = new SlicePredicate();
        SliceRange range = new SliceRange(ByteBufferUtil.bytes(""), ByteBufferUtil.bytes(""), false, MAX_NUMBER_COLUMNS);
        predicate.setSlice_range(range);
        ColumnParent parent = new ColumnParent(this.getColumnFamily());

        // Get this hour's
        List<ColumnOrSuperColumn> slice = getConnection(KEYSPACE).get_slice(ByteBufferUtil.bytes(thisHoursKey), parent,
                predicate, READ_CONSISTENCY);
        result.addAll(toLogEntry(thisHoursKey, slice));

        // Get previous hour's
        slice = getConnection(KEYSPACE).get_slice(ByteBufferUtil.bytes(previousHoursKey), parent, predicate,
                READ_CONSISTENCY);
        result.addAll(toLogEntry(previousHoursKey, slice));

        return result;
    }

    public boolean isMine(LogEntry logEntry) throws UnknownHostException, SocketException {
        return (logEntry.getHost().equals(getHostName()));
    }

    public boolean isOld(LogEntry logEntry) {
        long now = System.currentTimeMillis();
        long age = now - logEntry.getTimestamp();
        return (age > CommitLog.MAX_LOG_ENTRY_AGE);
    }
}


text:
@interface PNIdentificationViewController : UIViewController

@end