text:
.. _topics_convenience:

Convenience Functions
===========================================

.. contents::
    :depth: 2

You might be wondering: Can I use a dynamically-found app? What if I need a template object? Can I render a file directly?

Use the DMP convenience functions to be more dynamic, to interact directly with template objects, or to render a file of your choosing:

:Render a file from any app's template directory:
    .. code-block:: python

        from django_mako_plus import render_template
        mystr = render_template(request, 'homepage', 'index.html', context)

:Render a file from a custom directory within an app:
    .. code-block:: python

        from django_mako_plus import render_template
        mystr = render_template(request, 'homepage', 'custom.html', context, subdir="customsubdir")

:Render a file at any location, even outside of your project:
    .. code-block:: python

        from django_mako_plus import render_template_for_path
        mystr = render_template_for_path(request, '/var/some/dir/template.html', context)

:Get a template object for a template in an app:
    .. code-block:: python

        from django_mako_plus import get_template
        template = get_template('homepage', 'index.html')

:Get a template object at any location, even outside your project:
    .. code-block:: python

        from django_mako_plus import get_template_for_path
        template = get_template_for_path('/var/some/dir/template.html')

:Get a lower-level Mako template object (without the Django template wrapper):
    .. code-block:: python

        from django_mako_plus import get_template_for_path
        template = get_template_for_path('/var/some/dir/template.html')
        mako_template = template.mako_template

See the `Mako documentation <http://www.makotemplates.org/>`__ for more information on working directly with Mako template objects. Mako has many features that go well beyond the DMP interface.

The convenience functions are not Django-API compliant. To use the normal API, see `Django-Style Template Rendering <basics_django.html>`_.

    The convenience functions are perfectly fine to use, but ``request.dmp.render(...)``, described in the tutorial, is likely the best choice because it doesn't hard code the app name.


text:
package org.zstack.network.service.eip;

import org.apache.commons.net.util.SubnetUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.zstack.core.cloudbus.CloudBus;
import org.zstack.core.db.DatabaseFacade;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.errorcode.ErrorFacade;
import org.zstack.header.apimediator.ApiMessageInterceptionException;
import org.zstack.header.apimediator.ApiMessageInterceptor;
import org.zstack.header.apimediator.StopRoutingException;
import org.zstack.header.errorcode.SysErrors;
import org.zstack.header.message.APIMessage;
import org.zstack.header.vm.VmNicVO;
import org.zstack.header.vm.VmNicVO_;
import org.zstack.network.service.vip.VipState;
import org.zstack.network.service.vip.VipVO;

import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import java.util.concurrent.Callable;

/**
 */
public class EipApiInterceptor implements ApiMessageInterceptor {
    @Autowired
    private DatabaseFacade dbf;
    @Autowired
    private ErrorFacade errf;
    @Autowired
    private CloudBus bus;

    private void setServiceId(APIMessage msg) {
        if (msg instanceof EipMessage) {
            EipMessage emsg = (EipMessage) msg;
            bus.makeTargetServiceIdByResourceUuid(msg, EipConstant.SERVICE_ID, emsg.getEipUuid());
        }
    }

    @Override
    public APIMessage intercept(APIMessage msg) throws ApiMessageInterceptionException {
        if (msg instanceof APICreateEipMsg) {
            validate((APICreateEipMsg) msg);
        } else if (msg instanceof APIDeleteEipMsg) {
            validate((APIDeleteEipMsg) msg);
        } else if (msg instanceof APIDetachEipMsg) {
            validate((APIDetachEipMsg) msg);
        } else if (msg instanceof APIAttachEipMsg) {
            validate((APIAttachEipMsg) msg);
        } else if (msg instanceof APIGetEipAttachableVmNicsMsg) {
            validate((APIGetEipAttachableVmNicsMsg) msg);
        }

        setServiceId(msg);

        return msg;
    }

    private void validate(APIGetEipAttachableVmNicsMsg msg) {
        if (msg.getVipUuid() == null && msg.getEipUuid() == null) {
            throw new ApiMessageInterceptionException(errf.stringToInvalidArgumentError(
                    String.format("either eipUuid or vipUuid must be set")
            ));
        }

        if (msg.getEipUuid() != null) {
            SimpleQuery<EipVO> q = dbf.createQuery(EipVO.class);
            q.select(EipVO_.state, EipVO_.vmNicUuid);
            q.add(EipVO_.uuid, Op.EQ, msg.getEipUuid());
            Tuple t = q.findTuple();

            EipState state = t.get(0, EipState.class);
            if (state != EipState.Enabled) {
                throw new ApiMessageInterceptionException(errf.stringToOperationError(
                        String.format("eip[uuid:%s] is not in state of Enabled, cannot get attachable vm nic", msg.getEipUuid())
                ));
            }

            String vmNicUuid = t.get(1, String.class);
            if (vmNicUuid != null) {
                throw new ApiMessageInterceptionException(errf.stringToOperationError(
                        String.format("eip[uuid:%s] has attached to vm nic[uuid:%s], cannot get attachable vm nic", msg.getEipUuid(), vmNicUuid)
                ));
            }
        }
    }

    private void validate(final APIAttachEipMsg msg) {
        isVmNicUsed(msg.getVmNicUuid());

        SimpleQuery<EipVO> q = dbf.createQuery(EipVO.class);
        q.select(EipVO_.state, EipVO_.vmNicUuid, EipVO_.vipIp);
        q.add(EipVO_.uuid, Op.EQ, msg.getEipUuid());
        Tuple t = q.findTuple();
        String vmNicUuid = t.get(1, String.class);
        if (vmNicUuid != null) {
            throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR,
                    String.format("eip[uuid:%s] has attached to another vm nic[uuid:%s], can't attach again", msg.getEipUuid(), vmNicUuid)
            ));
        }

        EipState state = t.get(0, EipState.class);
        if (state != EipState.Enabled) {
            throw new ApiMessageInterceptionException(errf.stringToOperationError(
                    String.format("eip[uuid: %s] can only be attached when state is %s, current state is %s", msg.getEipUuid(), EipState.Enabled, state)
            ));
        }

        String vipIp = t.get(2, String.class);
        isVipInVmNicSubnet(vipIp, msg.getVmNicUuid());

        String vipL3Uuid = new Callable<String>() {
            @Override
            @Transactional(readOnly = true)
            public String call() {
                String sql = "select vip.uuid from VipVO vip, EipVO eip where vip.uuid = eip.vipUuid and eip.uuid = :eipUuid";
                TypedQuery<String> q = dbf.getEntityManager().createQuery(sql, String.class);
                q.setParameter("eipUuid", msg.getEipUuid());
                return q.getSingleResult();
            }
        }.call();

        SimpleQuery<VmNicVO> vq = dbf.createQuery(VmNicVO.class);
        vq.select(VmNicVO_.l3NetworkUuid);
        vq.add(VmNicVO_.uuid, Op.EQ, msg.getVmNicUuid());
        String guestL3Uuid = vq.findValue();
        if (guestL3Uuid.equals(vipL3Uuid)) {
            throw new ApiMessageInterceptionException(errf.stringToInvalidArgumentError(
                    String.format("guest l3Network of vm nic[uuid:%s] and vip l3Network of EIP[uuid:%s] are the same network",
                            msg.getVmNicUuid(), msg.getEipUuid())
            ));
        }
    }

    private void validate(APIDetachEipMsg msg) {
        SimpleQuery<EipVO> q = dbf.createQuery(EipVO.class);
        q.select(EipVO_.vmNicUuid);
        q.add(EipVO_.uuid, Op.EQ, msg.getUuid());
        String vmNicUuid = q.findValue();
        if (vmNicUuid == null) {
            throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR,
                    String.format("eip[uuid:%s] has not attached to any vm nic", msg.getUuid())
            ));
        }
    }

    private void validate(APIDeleteEipMsg msg) {
        if (!dbf.isExist(msg.getUuid(), EipVO.class)) {
            APIDeleteEipEvent evt = new APIDeleteEipEvent(msg.getId());
            bus.publish(evt);
            throw new StopRoutingException();
        }
    }

    private void isVmNicUsed(String vmNicUuid) {
        SimpleQuery<EipVO> eq = dbf.createQuery(EipVO.class);
        eq.select(EipVO_.uuid);
        eq.add(EipVO_.vmNicUuid, Op.EQ, vmNicUuid);
        String eipUuid = eq.findValue();
        if (eipUuid != null) {
            throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR,
                    String.format("vm nic[uuid:%s] has attached to another eip[uuid:%s]", vmNicUuid, eipUuid)
            ));
        }
    }

    private void isVipInVmNicSubnet(String eipIp, String vmNicUuid) {
        SimpleQuery<VmNicVO> q = dbf.createQuery(VmNicVO.class);
        q.select(VmNicVO_.gateway, VmNicVO_.netmask);
        q.add(VmNicVO_.uuid, Op.EQ, vmNicUuid);
        Tuple t = q.findTuple();
        String gw = t.get(0, String.class);
        String netmask = t.get(1, String.class);
        SubnetUtils sub = new SubnetUtils(gw, netmask);
        if (sub.getInfo().isInRange(eipIp)) {
            throw new ApiMessageInterceptionException(errf.stringToOperationError(
                    String.format("overlap public and private subnets. The subnet of EIP[%s] is an overlap with the subnet[%s/%s]" +
                            " of the VM nic[uuid:%s].", eipIp, gw, netmask, vmNicUuid)
            ));
        }
    }

    private void validate(APICreateEipMsg msg) {
        if (msg.getVmNicUuid() != null) {
            isVmNicUsed(msg.getVmNicUuid());
        }

        VipVO vip = dbf.findByUuid(msg.getVipUuid(), VipVO.class);
        if (vip.getUseFor() != null) {
            throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR,
                    String.format("vip[uuid:%s] has been occupied other network service entity[%s]", msg.getVipUuid(), vip.getUseFor())
            ));
        }

        if (vip.getState() != VipState.Enabled) {
            throw new ApiMessageInterceptionException(errf.instantiateErrorCode(SysErrors.OPERATION_ERROR,
                    String.format("vip[uuid:%s] is not in state[%s], current state is %s", msg.getVipUuid(), VipState.Enabled, vip.getState())
            ));
        }

        if (msg.getVmNicUuid() != null) {
            isVipInVmNicSubnet(vip.getIp(), msg.getVmNicUuid());

            SimpleQuery<VmNicVO> nicq = dbf.createQuery(VmNicVO.class);
            nicq.select(VmNicVO_.l3NetworkUuid);
            nicq.add(VmNicVO_.uuid, Op.EQ, msg.getVmNicUuid());
            String nicL3Uuid = nicq.findValue();
            if (nicL3Uuid.equals(vip.getL3NetworkUuid())) {
                throw new ApiMessageInterceptionException(errf.stringToInvalidArgumentError(
                        String.format("guest l3Network of vm nic[uuid:%s] and vip l3Network of vip[uuid: %s] are the same network", msg.getVmNicUuid(), msg.getVipUuid())
                ));
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package kafka

import (
	"fmt"
	"testing"
	"time"

	ab "github.com/hyperledger/fabric/protos/orderer"
	"github.com/hyperledger/fabric/protos/utils"

	"github.com/Shopify/sarama"
	"github.com/Shopify/sarama/mocks"
)

type mockConsumerImpl struct {
	consumedOffset int64
	chainPartition ChainPartition

	parentConsumer         *mocks.Consumer
	chainPartitionManager  *mocks.PartitionConsumer
	chainPartitionConsumer sarama.PartitionConsumer

	disk         chan *ab.KafkaMessage
	isSetup      chan struct{}
	targetOffset int64
	t            *testing.T
}

func mockNewConsumer(t *testing.T, cp ChainPartition, offset int64, disk chan *ab.KafkaMessage) (Consumer, error) {
	var err error
	parentConsumer := mocks.NewConsumer(t, nil)
	// NOTE The seek flag seems to be useless here.
	// The mock partition will have its highWatermarkOffset
	// initialized to 0 no matter what. I've opened up an issue
	// in the sarama repo: https://github.com/Shopify/sarama/issues/745
	// Until this is resolved, use the testFillWithBlocks() hack below.
	cpManager := parentConsumer.ExpectConsumePartition(cp.Topic(), cp.Partition(), offset)
	cpConsumer, err := parentConsumer.ConsumePartition(cp.Topic(), cp.Partition(), offset)
	// mockNewConsumer is basically a helper function when testing.
	// Any errors it generates internally, should result in panic
	// and not get propagated further; checking its errors in the
	// calling functions (i.e. the actual tests) increases boilerplate.
	if err != nil {
		t.Fatal("Cannot create mock partition consumer:", err)
	}
	mc := &mockConsumerImpl{
		consumedOffset: 0,
		targetOffset:   offset,
		chainPartition: cp,

		parentConsumer:         parentConsumer,
		chainPartitionManager:  cpManager,
		chainPartitionConsumer: cpConsumer,
		disk:    disk,
		isSetup: make(chan struct{}),
		t:       t,
	}
	// Stop-gap hack until sarama issue #745 is resolved:
	if mc.targetOffset >= testOldestOffset && mc.targetOffset <= (testNewestOffset-1) {
		mc.testFillWithBlocks(mc.targetOffset - 1) // Prepare the consumer so that the next Recv gives you blob #targetOffset
	} else {
		err = fmt.Errorf("Out of range offset (seek number) given to consumer: %d", offset)
		return mc, err
	}

	return mc, err
}

func (mc *mockConsumerImpl) Recv() <-chan *sarama.ConsumerMessage {
	if mc.consumedOffset >= testNewestOffset-1 {
		return nil
	}

	// This is useful in cases where we want to <-Recv() in a for/select loop in
	// a non-blocking manner. Without the timeout, the Go runtime will always
	// execute the body of the Recv() method. If there in no outgoing message
	// available, it will block while waiting on mc.disk. All the other cases in
	// the original for/select loop then won't be evaluated until we unblock on
	// <-mc.disk (which may never happen).
	select {
	case <-time.After(testTimePadding / 2):
	case outgoingMsg := <-mc.disk:
		mc.consumedOffset++
		mc.chainPartitionManager.YieldMessage(testNewConsumerMessage(mc.chainPartition, mc.consumedOffset, outgoingMsg))
		if mc.consumedOffset == mc.targetOffset-1 {
			close(mc.isSetup) // Hook for callers
		}
		return mc.chainPartitionConsumer.Messages()
	}

	return nil
}

func (mc *mockConsumerImpl) Errors() <-chan *sarama.ConsumerError {
	return nil
}

func (mc *mockConsumerImpl) Close() error {
	if err := mc.chainPartitionManager.Close(); err != nil {
		return err
	}
	return mc.parentConsumer.Close()
}

func (mc *mockConsumerImpl) testFillWithBlocks(offset int64) {
	for i := int64(1); i <= offset; i++ {
		go func() {
			mc.disk <- newRegularMessage(utils.MarshalOrPanic(newTestEnvelope(fmt.Sprintf("consumer fill-in %d", i))))
		}()
		<-mc.Recv()
	}
	return
}

func testNewConsumerMessage(cp ChainPartition, offset int64, kafkaMessage *ab.KafkaMessage) *sarama.ConsumerMessage {
	return &sarama.ConsumerMessage{
		Value:     sarama.ByteEncoder(utils.MarshalOrPanic(kafkaMessage)),
		Topic:     cp.Topic(),
		Partition: cp.Partition(),
		Offset:    offset,
	}
}


text:
Leap = require('leapjs');
//_ = Leap._;
_ = require('underscore'); // note that we require a newer version than Leap includes of underscore for throttle's {trailing: false}
recipe = require('./recipe.json');

// mac/linux only
var say = require('say');
//var loudness = require('loudness');  // https://github.com/LinusU/node-loudness

Leap.loop({enableGestures: true});

var Speaker = function(recipe){
  this.speech = null;

  this.directions = recipe.directions.split('.');
  this.directionsIndex = 0;

  console.log("Loaded recipe, " + this.directions.length + " sentences");
};

Speaker.prototype = {

  handleGesture: _.throttle(function(gesture){ // Reduce simultaneous fingers
    console.log('speed:', gesture.speed, 'gesture', gesture.id);

    if ( gesture.direction[0] > 0 ){ // check sign of x component
      this.sayNextLine(Math.abs(gesture.speed) - 30); // mm/s maps nicely to WPM
    }else{
      this.sayPreviousLine();
    }

  }, 2000, {trailing: false} ),

  sayPreviousLine: function(){
    if (this.speech){
      this.speech.kill('SIGHUP');
    }else {
      if (this.directionsIndex === 0) return;
      console.log('previous line');
      this.directionsIndex--;
    }
  },

  sayNextLine: function(rate){

    if (this.speech) this.speech.kill('SIGHUP');

    var text = this.directionsIndex === this.directions.length ? "All Done!" : this.directions[this.directionsIndex]; // may be off by one.

    console.log('next line: ' + text);

    this.speech = say.speak('Alex',
      text,
      _.bind(this.speakingDone, this),
      {rate: rate }
    );

    if (this.directionsIndex < this.directions.length) this.directionsIndex++;
  },

  speakingDone: function(){
    // note -this needs to be updated for concurrent async speech
    //this.speech = null;
  },

  loudnessError: function(){}

};

speaker = new Speaker(recipe);

Leap.loopController.on('gesture', function(gesture){
  //if (gesture.type != 'swipe' && gesture.type != 'update') console.log('u', gesture.id);
  if (gesture.type != 'swipe' || gesture.state != 'start') return;

  var hand = Leap.loopController.frame().hand(gesture.handIds[0]);

  if (hand.grabStrength > 0.7){
    console.log('rejecting due to high grabStrength: ' + hand.grabStrength);
    return
  }

  if (
    Math.abs(gesture.direction[0]) > Math.abs(gesture.direction[1]) &&
    Math.abs(gesture.direction[0]) > Math.abs(gesture.direction[2])
  ){
    speaker.handleGesture(gesture);
  }

});


text:
/*
        CHECDataBlock Ver. 3.6
*/

#ifndef CHECDataBlockH
#define CHECDataBlockH

#include <stdio.h>

const int hec_name_size = 40;
const int hec_str_size  = 256;

class CHECDataBlock {
 public:
  int data_type;
  CHECDataBlock(int dtype) : data_type(dtype) {}
  virtual ~CHECDataBlock() {}
  virtual void Clear()                     = 0;
  virtual void Write(class CHECData* hecd) = 0;
  virtual bool Read(class CHECData* hecd, char* header_line) = 0;
  virtual bool IsMesh() { return true; }
};

#endif


text:
module.exports = function(defaults) {
  var app = new EmberApp(defaults, {
    'ember-cli-preloader': {
      paths: {
        html: 'app/templates/misc/loading-bar.html',
        css: 'app/styles/animation/loading-bar.css'
      }
    }
  });

  return app.toTree();
}


text:
---
layout: post
title: Jekyll Theme - Curiosity and the power of change
category : Intro
tags : [intro, tag1, tag2]
stickie: true
---

## Desc

>This post is only for demo, some contents may be archived.
>
> Please check document for newest details:  [ Document](https://szhielelp.github.io/JekyllTheme-ProjectGaia-Docs/#/ )

## Update History

- May 30th, 2017
Added a reading progressbar for post page.

- May 6th, 2017
Updated font page
Added global font style

- April 3nd, 2017
Added new font

- Mar 5th, 2017
Updated style

- Mar 1st, 2017
Updated TOC plugin

- Feb 28th, 2017
Rebuild to include **Bootstrap 4-Alpha** and **JQuery 3**

## Desc

This is a personal blog source code.

The theme name is 'Curiosity and the power of change', cuz I have another under building project named 'Project Uranus' o(* ̄▽ ̄*)o

repo link: [szhielelp/JekyllTheme-ProjectGaia](http://localhost:4000)

## Post Example

Here is a post example

[Please check the code in Markdown]

## Plugins

### SyntaxHighlighter

Realized with this repo: [    syntaxhighlighter/syntaxhighlighter](https://github.com/syntaxhighlighter/syntaxhighlighter)

Usage(include necessary CSS and JS and run **SyntaxHighlighter.all()**):

      SyntaxHighlighter.all();

Here is code snippet example:

    [please check the post markdown here]

        List
        Link

### Table of Content

Realized with this repo: [    jgallen23/toc  ](https://github.com/jgallen23/toc)

![](   https://szhielelp.github.io/JekyllTheme-ProjectGaia/demo/X2.png   )

Auto-run when page loaded.

### md-post-header-collapse

Realized with this repo: [    szhielelp/md-post-header-collapse  ](https://github.com/szhielelp/md-post-header-collapse)

Run **$.headerCollapseRobot()** after post loaded.

    /*header collapsible example*/
    $.headerCollapseRobot(
      arr_Id_CollapseEnds =  new Array("end"),
      arr_Collapsible_Tag = new Array("H1","H2","H3"),
      arr_ExcludeElemPrefix_InCollapsible  = new Array("comment-"),
      arr_ExcludeElemPrefix_InCollapsing = new Array("sidebar-toc-Ik4D-")
    )

![](   https://szhielelp.github.io/JekyllTheme-ProjectGaia/demo/X1.png   )

You can try clicking on the icons near titles.

### Stickie Post

Just put a attribute in header of the specific post:

layout: post
title: blablablalala
category : Comic
tags : [Comic, 10101]
stickie: true

Then current post will show ahead of other posts.

### Reading Progressbar

Inspired from [http://es6.ruanyifeng.com/#docs/promise](http://es6.ruanyifeng.com/#docs/promise)

![](   https://szhielelp.github.io/JekyllTheme-ProjectGaia/demo/X4.png   )

It will show your reading progress for current post.


text:
//
//  NSDictionary+KYSAddition.h
//  KYSKitDemo
//
//  Created by Liu Zhao on 16/2/23.
//  Copyright © 2016年 Kang YongShuai. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface NSDictionary (KYSAddition)

#pragma mark - Dictionary Convertor
///=============================================================================
/// @name Dictionary Convertor
///=============================================================================

/**
 Creates and returns a dictionary from a specified property list data.

 @param plist   A property list data whose root object is a dictionary.
 @return A new dictionary created from the binary plist data, or nil if an error occurs.
 */
+ (NSDictionary *)dictionaryWithPlistData:(NSData *)plist;

/**
 Creates and returns a dictionary from a specified property list xml string.

 @param plist   A property list xml string whose root object is a dictionary.
 @return A new dictionary created from the plist string, or nil if an error occurs.

 @discussion Apple has implemented this method, but did not make it public.
 */
+ (NSDictionary *)dictionaryWithPlistString:(NSString *)plist;

/**
 Serialize the dictionary to a binary property list data.

 @return A binary plist data, or nil if an error occurs.

 @discussion Apple has implemented this method, but did not make it public.
 */
- (NSData *)plistData;

/**
 Serialize the dictionary to a xml property list string.

 @return A plist xml string, or nil if an error occurs.
 */
- (NSString *)plistString;

/**
 Returns a new array containing the dictionary's keys sorted.
 The keys should be NSString, and they will be sorted ascending.

 @return A new array containing the dictionary's keys,
 or an empty array if the dictionary has no entries.
 */
- (NSArray *)allKeysSorted;

/**
 Returns a new array containing the dictionary's values sorted by keys.

 The order of the values in the array is defined by keys.
 The keys should be NSString, and they will be sorted ascending.

 @return A new array containing the dictionary's values sorted by keys,
 or an empty array if the dictionary has no entries.
 */
- (NSArray *)allValuesSortedByKeys;

/**
 Returns a BOOL value tells if the dictionary has an object for key.

 @param key The key.
 */
- (BOOL)containsObjectForKey:(id)key;

/**
 Returns a new dictionary containing the entries for keys.
 If the keys is empty or nil, it just returns an empty dictionary.

 @param keys The keys.
 @return The entries for the keys.
 */
- (NSDictionary *)entriesForKeys:(NSArray *)keys;

/**
 Convert dictionary to json string. return nil if an error occurs.
 */
- (NSString *)jsonStringEncoded;

/**
 Convert dictionary to json string formatted. return nil if an error occurs.
 */
- (NSString *)jsonPrettyStringEncoded;

/**
 Try to parse an XML and wrap it into a dictionary.
 If you just want to get some value from a small xml, try this.

 example XML: "<config>link</config>"
 example Return: @{@"_name":@"config", @"a":{@"_text":@"link",@"href":@"test.com"}}

 @param xmlDataOrString XML in NSData or NSString format.
 @return Return a new dictionary, or nil if an error occurs.
 */
+ (NSDictionary *)dictionaryWithXML:(id)xmlDataOrString;

#pragma mark - Dictionary Value Getter
///=============================================================================
/// @name Dictionary Value Getter
///=============================================================================

- (BOOL)boolValueForKey:(NSString *)key default:(BOOL)def;

- (char)charValueForKey:(NSString *)key default:(char)def;
- (unsigned char)unsignedCharValueForKey:(NSString *)key default:(unsigned char)def;

- (short)shortValueForKey:(NSString *)key default:(short)def;
- (unsigned short)unsignedShortValueForKey:(NSString *)key default:(unsigned short)def;

- (int)intValueForKey:(NSString *)key default:(int)def;
- (unsigned int)unsignedIntValueForKey:(NSString *)key default:(unsigned int)def;

- (long)longValueForKey:(NSString *)key default:(long)def;
- (unsigned long)unsignedLongValueForKey:(NSString *)key default:(unsigned long)def;

- (long long)longLongValueForKey:(NSString *)key default:(long long)def;
- (unsigned long long)unsignedLongLongValueForKey:(NSString *)key default:(unsigned long long)def;

- (float)floatValueForKey:(NSString *)key default:(float)def;
- (double)doubleValueForKey:(NSString *)key default:(double)def;

- (NSInteger)integerValueForKey:(NSString *)key default:(NSInteger)def;
- (NSUInteger)unsignedIntegerValueForKey:(NSString *)key default:(NSUInteger)def;

- (NSNumber *)numverValueForKey:(NSString *)key default:(NSNumber *)def;
- (NSString *)stringValueForKey:(NSString *)key default:(NSString *)def;

@end

/**
 Provide some some common method for `NSMutableDictionary`.
 */
@interface NSMutableDictionary (YYAdd)

/**
 Creates and returns a dictionary from a specified property list data.

 @param plist   A property list data whose root object is a dictionary.
 @return A new dictionary created from the binary plist data, or nil if an error occurs.

 @discussion Apple has implemented this method, but did not make it public.
 */
+ (NSMutableDictionary *)dictionaryWithPlistData:(NSData *)plist;

/**
 Creates and returns a dictionary from a specified property list xml string.

 @param plist   A property list xml string whose root object is a dictionary.
 @return A new dictionary created from the plist string, or nil if an error occurs.
 */
+ (NSMutableDictionary *)dictionaryWithPlistString:(NSString *)plist;

/**
 Removes and returns the value associated with a given key.

 @param aKey The key for which to return and remove the corresponding value.
 @return The value associated with aKey, or nil if no value is associated with aKey.
 */
- (id)popObjectForKey:(id)aKey;

/**
 Returns a new dictionary containing the entries for keys, and remove these
 entries from receiver. If the keys is empty or nil, it just returns an
 empty dictionary.

 @param keys The keys.
 @return The entries for the keys.
 */
- (NSDictionary *)popEntriesForKeys:(NSArray *)keys;

@end


text:
<?php namespace Kouz;

class TextTruncator
{
    protected $ending = "";
    protected $limit = 0;

    protected function isLimitLessThanCharCount($text)
    {
        return ($this->limit > 0 && $this->limit < strlen($text));
    }
    protected function isLimitLessThanWordCount($text)
    {
        return ($this->limit > 0 && $this->limit < str_word_count($text));
    }

    protected function isWholeNumber($number)
    {
        return (is_numeric($number) && floor($number) == $number);
    }

    public function limitChars($text)
    {
        $this->validateText($text);
        $text = $this->sanitizeText($text);

        if ($this->isLimitLessThanCharCount($text)) {
            return trim(substr($text, 0, $this->limit)) . $this->ending;
        } else {
            return $text;
        }
    }

    public function limitWords($text)
    {
        $this->validateText($text);
        $text = $this->sanitizeText($text);

        if ($this->isLimitLessThanWordCount($text)) {
            $words = explode(" ", $text);
            return implode(" ", array_splice($words, 0, $this->limit)) . $this->ending;
        } else {
            return $text;
        }
    }

    public function setEnding($ending)
    {
        if (!is_string($ending)) {
            throw new \InvalidArgumentException("Ending must be a string");
        }

        $this->ending = $ending;
    }

    public function setLimit($limit)
    {
        if (!$this->isWholeNumber($limit)) {
            throw new \InvalidArgumentException("Limit must be a whole number");
        }

        $this->limit = $limit;
    }

    protected function sanitizeText($text)
    {
        $text = trim($text);
        $text = preg_replace('/\s+/', ' ', $text);

        return $text;
    }

    protected function validateText($text)
    {
        if (!is_string($text)) {
            throw new \InvalidArgumentException("Text must be a string");
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Scribbles</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="css/clean-blog.min.css" rel="stylesheet">

    <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
    <link href='https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation
                    Menu
                </button>
                Emmanuel Freddy

                        Home

                        Projects and Activites

                        Contact

Scribbles

                        Thoughts, Finds and Questions

                            Do we have to be in 2030 to appreciate Lebron James?

                            How does rosy retropection play a part in sports?

Posted by  Emmanuel Freddy on June 21, 2017

                            What challenges does a young Christian face on his/her spiritual journey?

                            A small glimpse from my perspective

Posted by Emmanuel Freddy on June 15, 2017


text:
package com.acme;

import java.util.logging.Logger;

/**
 * @version $Revision: $ $Date: $
 */
public enum State
{
  STOPPED, STARTING, RUNNING, STOPPING
}


text:
package io.jboot.apidoc;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.generator.ColumnMeta;
import com.jfinal.plugin.activerecord.generator.MetaBuilder;
import com.jfinal.plugin.activerecord.generator.TableMeta;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import io.jboot.Jboot;
import io.jboot.codegen.CodeGenHelpler;
import io.jboot.db.datasource.DataSourceConfig;
import io.jboot.db.driver.DriverClassNames;
import io.jboot.utils.DateUtil;
import io.jboot.utils.FileUtil;
import io.jboot.utils.StrUtil;

import javax.sql.DataSource;
import java.io.File;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.temporal.Temporal;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class ApiJsonGenerator {

    /**
     * 生成 Mock Json 数据
     */
    public static void genMockJson() {
        genMockJson(new JsonGeneratorConfig("api-mock.json"));
    }

    /**
     * 生成 Mock Json 数据
     *
     * @param config
     */
    public static void genMockJson(JsonGeneratorConfig config) {

        Map<String, Map<String, Object>> root = new LinkedHashMap<>();

        File file = new File(config.getJsonFilePathPathAbsolute());
        //如果文件存在,则先读取其配置,然后再修改
        if (file.exists()) {
            String oldJson = FileUtil.readString(file);
            JSONObject rootJsonObject = JSONObject.parseObject(oldJson, Feature.OrderedField);
            if (rootJsonObject != null && !rootJsonObject.isEmpty()) {
                for (String classOrSimpleName : rootJsonObject.keySet()) {
                    root.put(classOrSimpleName, rootJsonObject.getJSONObject(classOrSimpleName));
                }
            }
        }

        MetaBuilder builder = CodeGenHelpler.createMetaBuilder(config.getDatasource(), config.getType(), false);
        List<TableMeta> tableMetas = builder.build();

        if (config.tableMetaFilter != null) {
            tableMetas = tableMetas.stream()
                    .filter(config.tableMetaFilter)
                    .collect(Collectors.toList());
        }

        for (TableMeta tableMeta : tableMetas) {
            Map<String, Object> classMockData = new LinkedHashMap<>();
            for (ColumnMeta columnMeta : tableMeta.columnMetas) {
                Object mockData = createMockData(columnMeta);
                if (mockData != null && !"".equals(mockData)) {
                    classMockData.put(columnMeta.attrName, mockData);
                }
            }
            if (!classMockData.isEmpty()) {
                root.put(StrKit.firstCharToLowerCase(tableMeta.modelName), classMockData);
            }
        }

        String jsonContent = JSONObject.toJSONString(root, true);
        FileUtil.writeString(file, jsonContent);

        System.out.println("Gen Remarks Json File ----->" + FileUtil.getCanonicalPath(file));
    }

    private static Object createMockData(ColumnMeta columnMeta) {
        if (String.class.getName().equals(columnMeta.javaType)) {
            return columnMeta.remarks;
        } else if (Date.class.getName().equals(columnMeta.javaType)) {
            return DateUtil.toDateTimeString(new Date());
        } else if (isTemporal(columnMeta.javaType)) {
            return DateUtil.toDateTimeString(new Date());
        } else if (int.class.getName().equals(columnMeta.javaType)) {
            return 1;
        } else if (Integer.class.getName().equals(columnMeta.javaType)) {
            return 100;
        } else if (long.class.getName().equals(columnMeta.javaType)) {
            return 1;
        } else if (Long.class.getName().equals(columnMeta.javaType)) {
            return 100;
        } else if (short.class.getName().equals(columnMeta.javaType)) {
            return 1;
        } else if (Short.class.getName().equals(columnMeta.javaType)) {
            return 100;
        } else if (BigDecimal.class.getName().equals(columnMeta.javaType)) {
            return BigDecimal.ONE;
        } else if (BigInteger.class.getName().equals(columnMeta.javaType)) {
            return BigDecimal.ONE;
        } else if (boolean.class.getName().equals(columnMeta.javaType)) {
            return Boolean.TRUE;
        } else if (Boolean.class.getName().equals(columnMeta.javaType)) {
            return Boolean.TRUE;
        } else if (float.class.getName().equals(columnMeta.javaType)) {
            return 1.0f;
        } else if (Float.class.getName().equals(columnMeta.javaType)) {
            return 1.0f;
        } else if (double.class.getName().equals(columnMeta.javaType)) {
            return 1.0d;
        } else if (Double.class.getName().equals(columnMeta.javaType)) {
            return 1.0d;
        } else {
            return "";
        }
    }

    private static boolean isTemporal(String javaType) {
        try {
            return Temporal.class.isAssignableFrom(Class.forName(javaType));
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 生成 Model 的字段备注数据
     */
    public static void genRemarksJson() {
        genRemarksJson(new JsonGeneratorConfig("api-remarks.json"));
    }

    /**
     * 生成 Model 的字段备注数据
     */
    public static void genRemarksJson(JsonGeneratorConfig config) {

        Map<String, Map<String, String>> root = new LinkedHashMap<>();

        File file = new File(config.getJsonFilePathPathAbsolute());
        //如果文件存在,则先读取其配置,然后再修改
        if (file.exists()) {
            String oldJson = FileUtil.readString(file);
            JSONObject rootJsonObject = JSONObject.parseObject(oldJson, Feature.OrderedField);
            if (rootJsonObject != null && !rootJsonObject.isEmpty()) {
                for (String classOrSimpleName : rootJsonObject.keySet()) {
                    Map<String, String> remarks = new LinkedHashMap<>();
                    JSONObject modelRemarks = rootJsonObject.getJSONObject(classOrSimpleName);
                    modelRemarks.forEach((k, v) -> remarks.put(k, String.valueOf(v)));
                    root.put(classOrSimpleName, remarks);
                }
            }
        }

        MetaBuilder builder = CodeGenHelpler.createMetaBuilder(config.getDatasource(), config.getType(), false);
        List<TableMeta> tableMetas = builder.build();

        if (config.tableMetaFilter != null) {
            tableMetas = tableMetas.stream()
                    .filter(config.tableMetaFilter)
                    .collect(Collectors.toList());
        }

        for (TableMeta tableMeta : tableMetas) {
            Map<String, String> modelRemarks = new LinkedHashMap<>();
            for (ColumnMeta columnMeta : tableMeta.columnMetas) {
                if (StrUtil.isNotBlank(columnMeta.remarks)) {
                    modelRemarks.put(columnMeta.attrName, columnMeta.remarks);
                }
            }
            if (!modelRemarks.isEmpty()) {
                root.put(StrKit.firstCharToLowerCase(tableMeta.modelName), modelRemarks);
            }
        }

        String jsonContent = JSONObject.toJSONString(root, true);
        FileUtil.writeString(file, jsonContent);

        System.out.println("Gen Remarks Json File ----->" + FileUtil.getCanonicalPath(file));
    }

    public static class JsonGeneratorConfig {

        private boolean useJbootDatasource = true;

        private String jdbcUrl;
        private String userName;
        private String password;
        private String type = DataSourceConfig.TYPE_MYSQL;

        private String jsonFilePath;
        private Predicate<TableMeta> tableMetaFilter;

        public JsonGeneratorConfig() {
        }

        public JsonGeneratorConfig(String jsonFilePath) {
            this.jsonFilePath = jsonFilePath;
        }

        public boolean isUseJbootDatasource() {
            return useJbootDatasource;
        }

        public void setUseJbootDatasource(boolean useJbootDatasource) {
            this.useJbootDatasource = useJbootDatasource;
        }

        public String getJdbcUrl() {
            return jdbcUrl;
        }

        public void setJdbcUrl(String jdbcUrl) {
            this.jdbcUrl = jdbcUrl;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getJsonFilePath() {
            return jsonFilePath;
        }

        public void setJsonFilePath(String jsonFilePath) {
            this.jsonFilePath = jsonFilePath;
        }

        public String getJsonFilePathPathAbsolute() {
            if (FileUtil.isAbsolutePath(jsonFilePath)) {
                return jsonFilePath;
            }
            return FileUtil.getCanonicalPath(new File(PathKit.getRootClassPath(), "../../" + jsonFilePath));
        }

        public Predicate<TableMeta> getTableMetaFilter() {
            return tableMetaFilter;
        }

        public void setTableMetaFilter(Predicate<TableMeta> tableMetaFilter) {
            this.tableMetaFilter = tableMetaFilter;
        }

        public DataSource getDatasource() {
            if (useJbootDatasource) {
                DataSourceConfig datasourceConfig = Jboot.config(DataSourceConfig.class, "jboot.datasource");
                HikariConfig config = new HikariConfig();
                config.setJdbcUrl(datasourceConfig.getUrl());
                config.setUsername(datasourceConfig.getUser());
                config.setPassword(datasourceConfig.getPassword());
                config.setDriverClassName(datasourceConfig.getDriverClassName());

                return new HikariDataSource(config);
            } else {
                HikariConfig config = new HikariConfig();
                config.setJdbcUrl(this.jdbcUrl);
                config.setUsername(this.userName);
                config.setPassword(this.password);
                config.setDriverClassName(DriverClassNames.getDefaultDriverClass(this.type));

                return new HikariDataSource(config);
            }
        }
    }
}


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//*********************************************************

using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Effects;
using Microsoft.Graphics.Canvas.UI.Composition;
using SamplesCommon;
using SamplesCommon.ImageLoader;
using System;
using System.Numerics;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.DirectX;
using Windows.UI;
using Windows.UI.Composition;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Hosting;

namespace CompositionSampleGallery
{
    public sealed partial class Z_OrderScrolling : SamplePage
    {
        public Z_OrderScrolling()
        {
            this.InitializeComponent();
            this.Loaded += MainPage_Loaded;
            this.Unloaded += MainPage_Unloaded;
        }

        public static string        StaticSampleName    { get { return "Z-Order Scrolling"; } }
        public override string      SampleName          { get { return StaticSampleName; } }
        public override string      SampleDescription   { get { return "Demonstrates how to use a ScrollViewer and ExpressionAnimations to drive Visual properties like Scale, Offset, and Opacity based off of the scroll position. Especially notice how the profile image swaps underneath the header."; } }
        public override string      SampleCodeUri       { get { return "http://go.microsoft.com/fwlink/p/?LinkID=761168"; } }

        /// <summary>
        /// MainPage_Loaded is used for all of our initialization to keep the UI thread mostly free.
        /// </summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private async void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            _compositor = ElementCompositionPreview.GetElementVisual(sender as UIElement).Compositor;
            _imageLoader = ImageLoaderFactory.CreateImageLoader(_compositor);
            var scrollProperties = ElementCompositionPreview.GetScrollViewerManipulationPropertySet(Scroller);

            var uri = new Uri("ms-appx:///Samples/SDK 10586/Z-Order Scrolling/RollingWaves.jpg");
            ParallaxingImage.Source = uri;
            ParallaxingImage.Brush = await InitializeCrossFadeEffect(uri);

            var maskedBrush = InitializeCompositeEffect();

            ParallaxingImage.SizeChanged += (s, ev) => { UpdateSizes(); };

            InitializeBackgroundImageVisual(scrollProperties);
            InitializeFrontVisual(scrollProperties, maskedBrush);
            InitializeBehindVisual(scrollProperties, maskedBrush);

            UpdateSizes();
        }

        /// <summary>
        /// MainPage_Unloaded is used to dispose of the ManagedSurfaces.
        /// </summary>
        /// <param name="sender">not used</param>
        /// <param name="e">not used</param>
        private void MainPage_Unloaded(object sender, RoutedEventArgs e)
        {
            _profilePictureSurface.Dispose();
            _circleMaskSurface.Dispose();
            _imageLoader.Dispose();
        }

        /// <summary>
        /// Create the Visual that will host the profile background image and setup
        /// the animations that will drive it.
        /// </summary>
        /// /// <param name="scrollProperties">A property set who has Translation.Y specified - typically the return from ElementCompositionPreview.GetScrollViewerManipulationPropertySet(...).</param>
        private void InitializeBackgroundImageVisual(CompositionPropertySet scrollProperties)
        {
            //
            // Get the visual for the background image, and let it parallax up until the BackgroundPeekSize.
            // BackgroundPeekSize is later defined as the amount of the image to leave showing.
            //
            _backgroundVisual = ElementCompositionPreview.GetElementVisual(ParallaxingImage);

            //
            // If the scrolling is positive (i.e., bouncing), don't translate at all.  Then check to see if
            // we have parallaxed as far as we should go.  If we haven't, keep parallaxing otherwise use
            // the scrolling translation to keep the background stuck with the background peeking out.
            //
            _backgroundTranslationAnimation = _compositor.CreateExpressionAnimation(
                "BaseOffset + (scrollingProperties.Translation.Y > 0 ? 0 : " +
                    "( (1-ParallaxRatio) * -scrollingProperties.Translation.Y) < BackgroundPeekSize ? " +
                            "(ParallaxRatio * -scrollingProperties.Translation.Y) : -BackgroundPeekSize-scrollingProperties.Translation.Y)");
            _backgroundTranslationAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);
            _backgroundTranslationAnimation.SetScalarParameter("ParallaxRatio", _parallaxRatio);

            _backgroundScaleAnimation = _compositor.CreateExpressionAnimation(
                "Lerp(" +
                        "1," +
                        "1+Amount," +
                        "Clamp(scrollingProperties.Translation.Y/50,0,1)" +
                    ")");
            _backgroundScaleAnimation.SetScalarParameter("Amount", _backgroundScaleAmount);
            _backgroundScaleAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);

            _backgroundBlurAnimation = _compositor.CreateExpressionAnimation(
                "Clamp(-scrollingProperties.Translation.Y / (BackgroundPeekSize * .5),0,1)");
            _backgroundBlurAnimation.SetScalarParameter("Amount", _backgroundScaleAmount);
            _backgroundBlurAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);

            _backgroundInverseBlurAnimation = _compositor.CreateExpressionAnimation(
                "1-Clamp(-scrollingProperties.Translation.Y / (BackgroundPeekSize * .5),0,1)");
            _backgroundInverseBlurAnimation.SetScalarParameter("Amount", _backgroundScaleAmount);
            _backgroundInverseBlurAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);

            //
            // We want to keep the Name/Title text in the middle of the background image.  To start with,
            // we add the centerpoint - since we move the anchor point to (.5,/5) which XAML layout doesn't
            // expect - and the background offset offset to keep the element positioned with the background.
            // we then lerp between its existing position and its final position based on parallaxed distance
            // traveled.
            //
            _profileContentVisual = ElementCompositionPreview.GetElementVisual(ProfileContent);
            _profileContentTranslationAnimation = _compositor.CreateExpressionAnimation(
                "(-scrollingProperties.Translation.Y + Background.Offset.Y + Background.Size.Y/2)/2");
            _profileContentTranslationAnimation.SetReferenceParameter("Background", _backgroundVisual);
            _profileContentTranslationAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);

            _profileContentScaleAnimation = _compositor.CreateExpressionAnimation(
                    "Lerp(1,ShrinkRatio, " +
                        "Clamp( (Background.Offset.Y - Background.Size.Y/2) / (Background.Size.Y - BackgroundPeekSize),0,1))"
                );
            _profileContentScaleAnimation.SetScalarParameter("ShrinkRatio", _contentShrinkRatio);
            _profileContentScaleAnimation.SetReferenceParameter("Background", _backgroundVisual);
        }

        /// <summary>
        /// Create the _frontVisual and the animations that drive it.
        /// </summary>
        /// <param name="scrollProperties">A property set who has Translation.Y specified - typically the return from ElementCompositionPreview.GetScrollViewerManipulationPropertySet(...).</param>
        /// <param name="maskedBrush">This is the brush that will be set on _frontVisual</param>
        private void InitializeFrontVisual(CompositionPropertySet scrollProperties, CompositionEffectBrush maskedBrush)
        {
            //
            // Create  the _frontVisual, set the brush on it, and attach it to the scrollViewer.  Setting it as the
            // child visual on scrollviewer will put it in front of all the scrollViewer content.
            //
            _frontVisual = _compositor.CreateSpriteVisual();
            _frontVisual.Brush = maskedBrush;
            ElementCompositionPreview.SetElementChildVisual(MainGrid, _frontVisual);

            //
            // "Terms" in the following expression:
            //
            //      (CrossoverTranslation + scrollingProperties.Translation.Y)/CrossoverTranslation
            //
            //              Since scrollingProperties.Translation.Y is negative.  This creates a normalized value that goes from
            //              0 to 1 between no scrolling and the CrossoverTranslation.
            //
            _frontPropertiesScalarScaleAnimation = _compositor.CreateExpressionAnimation(
                    "Lerp(minClamp, maxClamp, Clamp((CrossoverTranslation + scrollingProperties.Translation.Y)/CrossoverTranslation,0,1))"
                );
            _frontPropertiesScalarScaleAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);
            _frontPropertiesScalarScaleAnimation.SetScalarParameter("minClamp", _finalScaleAmount);
            _frontPropertiesScalarScaleAnimation.SetScalarParameter("maxClamp", _initialScaleAmount);

            //
            // The previous equation calculates a scalar which is later bound to ScalarScale in FrontVisual's Properties.
            // This equation uses that scalar to construct a new vector3 to set to animate the scale of the visual itself.
            //
            var vector3ScaleAnimation = _compositor.CreateExpressionAnimation("Vector3(Properties.ScalarScale, Properties.ScalarScale, 1)");
            _frontVisual.Properties.InsertScalar("ScalarScale", 1);
            vector3ScaleAnimation.SetReferenceParameter("Properties", _frontVisual.Properties);
            _frontVisual.StartAnimation("Scale", vector3ScaleAnimation);

            //
            // This equation controls whether or not the FrontVisual is visibile via opacity.  It uses a simple ternary operator
            // to pick between 100% and 0% opacity based on the position being before the crossover point.
            //
            _frontVisibilityAnimation =
                _compositor.CreateExpressionAnimation("-scrollingProperties.Translation.Y <= CrossoverTranslation ? 1 : 0");
            _frontVisibilityAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);

            _frontTranslationAnimation =
                _compositor.CreateExpressionAnimation("scrollingProperties.Translation.Y > 0 ? BaseOffset : BaseOffset-scrollingProperties.Translation.Y");
            _frontTranslationAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);

        }

        /// <summary>
        /// Create the _backVisual and the animations that drive it.
        /// </summary>
        /// <param name="scrollProperties">A property set who has Translation.Y specified - typically the return from ElementCompositionPreview.GetScrollViewerManipulationPropertySet(...).</param>
        /// <param name="maskedBrush">This is the brush that will be set on _frontVisual</param>
        private void InitializeBehindVisual(CompositionPropertySet scrollProperties, CompositionEffectBrush maskedBrush)
        {
            //
            // Create  the _frontVisual, set the brush on it, and attach it to the BackGrid.  BackGrid is an empty grid
            // that is visually behind the profile background (the waves). Therefore, setting it as the
            // child visual on the BackGrid will put it behind all the scrollViewer content.
            //
            _backVisual = _compositor.CreateSpriteVisual();
            _backVisual.Brush = maskedBrush;
            ElementCompositionPreview.SetElementChildVisual(BackGrid, _backVisual);

            //
            // This equation controls whether or not the FrontVisual is visibile via opacity.  It uses a simple ternary operator
            // to pick between 100% and 0% opacity based on the position being after the crossover point.
            //
            _backVisual.Scale = new Vector3(_finalScaleAmount, _finalScaleAmount, 1);
            _behindOpacityAnimation = _compositor.CreateExpressionAnimation("-scrollingProperties.Translation.Y <= CrossoverTranslation ? 0 : 1");
            _behindOpacityAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);

            //
            // "Terms" and explanation of the following expression:
            //
            //      (initialOffset - scrollingProperties.Translation.Y)
            //
            //              Since _backVisual is a child of the scroller, the initial position minus the scrolling offset keeps the content
            //              in its original location.
            //
            //      2 * (CrossoverTranslation + scrollingProperties.Translation.Y)
            //
            //              Since scrollingProperties.Translation.Y is negative when this expression is visibile, this term calculates the
            //              distance past the crossover point and scales it.  The scale causes the content to move faster than the scrolling.
            //              Since this term evaluates to zero at the crossover point and the term above keeps the content from moving, when
            //              the visibility swaps between frontVisual and backVisual, they are perfectly aligned.
            //
            _behindTranslateAnimation = _compositor.CreateExpressionAnimation(
            "(BaseOffset - scrollingProperties.Translation.Y) + 2 * (CrossoverTranslation + scrollingProperties.Translation.Y)");
            _behindTranslateAnimation.SetReferenceParameter("scrollingProperties", scrollProperties);
        }

        private void UpdateSizes()
        {
            //
            // First, calculate all of the new sizes and distances we will need.
            //
            var backgroundImageSize = new Vector2((float)ParallaxingImage.ActualWidth, (float)ParallaxingImage.ActualHeight);
            var profileImageSize = new Vector2((float)ParallaxingImage.ActualWidth, (float)ParallaxingImage.ActualHeight) * _initialScaleAmount;
            var crossoverTranslation = (profileImageSize.Y * _finalScaleAmount / 2 + _followMargin) / (1 - _parallaxRatio);
            var offset = new Vector3((float)ParallaxingImage.ActualWidth / 2, (float)ParallaxingImage.ActualHeight, 0);
            var backgroundPeekSize = backgroundImageSize.Y * _backgroundShowRatio;

            // Push the text content down to make room for the image overhanging.
            //
            ContentPanel.Margin = new Thickness(5, (float)ParallaxingImage.ActualHeight + profileImageSize.Y / 2, 5, 5);

            //
            // Resolve all of the property parameters and references on the frontVisual animations and start them.
            //
            _frontVisual.AnchorPoint = new Vector2(.5f, .5f);
            _frontVisual.Offset = offset;
            _frontVisual.Size = profileImageSize;
            _frontTranslationAnimation.SetScalarParameter("BaseOffset", offset.Y);
            _frontPropertiesScalarScaleAnimation.SetScalarParameter("CrossoverTranslation", crossoverTranslation);
            _frontVisibilityAnimation.SetScalarParameter("CrossoverTranslation", crossoverTranslation);
            _frontVisual.Properties.StartAnimation("ScalarScale", _frontPropertiesScalarScaleAnimation);
            _frontVisual.StartAnimation("Opacity", _frontVisibilityAnimation);
            _frontVisual.StartAnimation("Offset.Y", _frontTranslationAnimation);

            //
            // Resolve all of the property parameters and references on the backVisual animations and start them.
            //
            _backVisual.AnchorPoint = new Vector2(.5f, .5f);
            _backVisual.Offset = offset;
            _backVisual.Size = profileImageSize;
            _behindTranslateAnimation.SetScalarParameter("BaseOffset", offset.Y);
            _behindTranslateAnimation.SetScalarParameter("CrossoverTranslation", crossoverTranslation);
            _behindOpacityAnimation.SetScalarParameter("CrossoverTranslation", crossoverTranslation);

            _backVisual.StartAnimation("Opacity", _behindOpacityAnimation);
            _backVisual.StartAnimation("Offset.Y", _behindTranslateAnimation);

            //
            // Resolve all property parameters and references on _backgroundVisual
            //
            _backgroundTranslationAnimation.SetScalarParameter("BackgroundPeekSize", backgroundPeekSize);
            _backgroundVisual.Size = backgroundImageSize;
            _backgroundVisual.AnchorPoint = new Vector2(.5f, .5f);
            _backgroundVisual.CenterPoint = new Vector3(backgroundImageSize / 2, 1);
            _backgroundTranslationAnimation.SetScalarParameter("BaseOffset", backgroundImageSize.Y / 2);
            _backgroundVisual.Offset = new Vector3(backgroundImageSize / 2, 0);
            _backgroundVisual.StartAnimation("Offset.Y", _backgroundTranslationAnimation);
            _backgroundVisual.StartAnimation("Scale.X", _backgroundScaleAnimation);
            _backgroundVisual.StartAnimation("Scale.Y", _backgroundScaleAnimation);

            _backgroundBlurAnimation.SetScalarParameter("BackgroundPeekSize", backgroundPeekSize);
            _backgroundInverseBlurAnimation.SetScalarParameter("BackgroundPeekSize", backgroundPeekSize);
            ParallaxingImage.Brush.StartAnimation("Arithmetic.Source1Amount", _backgroundInverseBlurAnimation);
            ParallaxingImage.Brush.StartAnimation("Arithmetic.Source2Amount", _backgroundBlurAnimation);

            //
            // Resolve all property parameters and references on _profileContentVisual
            //
            _profileContentVisual.Size = new Vector2((float)ProfileContent.ActualWidth, (float)ProfileContent.ActualHeight);
            _profileContentVisual.AnchorPoint = new Vector2(0.5f, 0f);
            _profileContentVisual.Offset = new Vector3(0);
            _profileContentVisual.Offset = new Vector3(_profileContentVisual.Size / 2, 0);
            _profileContentScaleAnimation.SetScalarParameter("BackgroundPeekSize", backgroundPeekSize);
            _profileContentVisual.StartAnimation("Offset.Y", _profileContentTranslationAnimation);
            _profileContentVisual.StartAnimation("Scale.X", _profileContentScaleAnimation);
            _profileContentVisual.StartAnimation("Scale.Y", _profileContentScaleAnimation);
        }

        /// <summary>
        /// Function is responsible for creating the circular alpha masked profile brush
        /// </summary>
        /// <returns></returns>
        private CompositionEffectBrush InitializeCompositeEffect()
        {
            //
            // Create a simple Composite Effect, using DestinationIn (S * DA), and two named sources - image and mask.
            //
            var effect = new CompositeEffect
            {
                Mode = CanvasComposite.DestinationIn,
                Sources =
                {
                    new CompositionEffectSourceParameter("image"),
                    new CompositionEffectSourceParameter("mask")
                }

            };
            var factory = _compositor.CreateEffectFactory(effect);
            var brush = factory.CreateBrush();

            //
            // Load in the profile picture as a brush using the Composition Toolkit.
            //
            CompositionSurfaceBrush profileBrush = _compositor.CreateSurfaceBrush();
            _profilePictureSurface = _imageLoader.CreateManagedSurfaceFromUri(new Uri("ms-appx:///Samples/SDK 10586/Z-Order Scrolling/teched3ae5a27b-4f78-e111-94ad-001ec953730b.jpg"));
            profileBrush.Surface = _profilePictureSurface.Surface;
            brush.SetSourceParameter("image", profileBrush);

            //
            // Load in the circular mask picture asx a brush using the composition Toolkit.
            //
            CompositionSurfaceBrush maskBrush = _compositor.CreateSurfaceBrush();
            _circleMaskSurface = _imageLoader.CreateCircleSurface(200, Colors.White);
            maskBrush.Surface = _circleMaskSurface.Surface;
            brush.SetSourceParameter("mask", maskBrush);

            return brush;

        }

        /// <summary>
        /// Function is responsible for creating the circular alpha masked profile brush
        /// </summary>
        /// <returns></returns>
        private async Task<CompositionEffectBrush> InitializeCrossFadeEffect(Uri uri)
        {
            var graphicsEffect = new ArithmeticCompositeEffect
            {
                Name = "Arithmetic",
                Source1 = new CompositionEffectSourceParameter("ImageSource"),
                Source1Amount = 1,
                Source2 = new CompositionEffectSourceParameter("BlurImage"),
                Source2Amount = 0,
                MultiplyAmount = 0
            };

            var factory = _compositor.CreateEffectFactory(graphicsEffect, new[] { "Arithmetic.Source1Amount", "Arithmetic.Source2Amount" });

            CompositionDrawingSurface blurSurface = await SurfaceLoader.LoadFromUri(uri, Size.Empty, ApplyBlurEffect);
            CompositionEffectBrush crossFadeBrush = factory.CreateBrush(); ;
            crossFadeBrush.SetSourceParameter("ImageSource", ParallaxingImage.SurfaceBrush);
            crossFadeBrush.SetSourceParameter("BlurImage", _compositor.CreateSurfaceBrush(blurSurface));

            return crossFadeBrush;
        }

        CompositionDrawingSurface ApplyBlurEffect(CanvasBitmap bitmap, Windows.UI.Composition.CompositionGraphicsDevice device, Size sizeTarget)
        {
            GaussianBlurEffect blurEffect = new GaussianBlurEffect()
            {
                Source = bitmap,
                BlurAmount = 20.0f,
                BorderMode = EffectBorderMode.Hard,
            };

            float fDownsample = .3f;
            Size sizeSource = bitmap.Size;
            if (sizeTarget == Size.Empty)
            {
                sizeTarget = sizeSource;
            }

            sizeTarget = new Size(sizeTarget.Width * fDownsample, sizeTarget.Height * fDownsample);
            CompositionDrawingSurface blurSurface = device.CreateDrawingSurface(sizeTarget, DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
            using (var ds = CanvasComposition.CreateDrawingSession(blurSurface))
            {
                Rect destination = new Rect(0, 0, sizeTarget.Width, sizeTarget.Height);
                ds.Clear(Windows.UI.Color.FromArgb(255, 255, 255, 255));
                ds.DrawImage(blurEffect, destination, new Rect(0, 0, sizeSource.Width, sizeSource.Height));
            }

            return blurSurface;
        }

        private Compositor _compositor;
        private IImageLoader _imageLoader;

        private SpriteVisual _backVisual;
        private ExpressionAnimation _behindOpacityAnimation;
        private ExpressionAnimation _behindTranslateAnimation;

        private SpriteVisual _frontVisual;
        private ExpressionAnimation _frontTranslationAnimation;
        private ExpressionAnimation _frontPropertiesScalarScaleAnimation;
        private ExpressionAnimation _frontVisibilityAnimation;

        private Visual _backgroundVisual;
        private ExpressionAnimation _backgroundTranslationAnimation;
        private ExpressionAnimation _backgroundScaleAnimation;
        private ExpressionAnimation _backgroundBlurAnimation;
        private ExpressionAnimation _backgroundInverseBlurAnimation;

        private Visual _profileContentVisual;
        private ExpressionAnimation _profileContentTranslationAnimation;
        private ExpressionAnimation _profileContentScaleAnimation;

        private ICircleSurface _circleMaskSurface;
        private IManagedSurface _profilePictureSurface;

        private float _initialScaleAmount = .8f;
        private float _finalScaleAmount = .4f;
        private float _followMargin = 20f;
        private float _backgroundShowRatio = .7f;
        private float _backgroundScaleAmount = .25f;
        private float _parallaxRatio = .2f;
        private float _contentShrinkRatio = .7f;
    }
}


text:
Rails.application.routes.draw do
  resources :candy_charts, only: [:index, :show], controller: "candy_charts"
end


text:
MongoCollection::getSlaveOkay()
--DESCRIPTION--
Test both true and false for slave_okay attribute
--SKIPIF--
<?php require_once dirname(__FILE__) ."/skipif.inc"; ?>
--FILE--
<?php
require_once dirname(__FILE__) . "/../utils.inc";
$m = mongo();

$c = $m->phpunit->col;
$c->setSlaveOkay((bool) array('foo'));
var_dump($c->getSlaveOkay());
$c->setSlaveOkay((bool) null);
var_dump($c->getSlaveOkay());
?>
--EXPECTF--
%s: Function MongoCollection::setSlaveOkay() is deprecated in %s on line %d

%s: Function MongoCollection::getSlaveOkay() is deprecated in %s on line %d
bool(true)

%s: Function MongoCollection::setSlaveOkay() is deprecated in %s on line %d

%s: Function MongoCollection::getSlaveOkay() is deprecated in %s on line %d
bool(false)


text:
Homerun est une application permettant une fois défini l'emplacement de son domicile ou lieu de résidence de retrouver son chemin facilement. En cas de problème ou à titre préventif, il est possible d'envoyer à un proche un sms donnant votre localisation et indiquant que vous êtes sur le chemin du retour.

Homerun utilisera donc les fonctionnalités suivantes :
 * Géolocalisation
 * Bing map direction
 * Envoi de messages
 * Gestion de contacts

## Comment marche l'application ?

Avant d'utiliser les services proposés, il est important de vérifier plusieurs choses. La première est que la localisation est bien activé sur votre téléphone. Sans cela, les fonctionnalités proposés vous seront bloqués. De même, l'information a besoin d'un minimum de données pour pouvoir être utilisé pleinement. Il suffit donc simplement d'aller dans la page des paramètres en cliquant sur le bouton « Mes paramètres » et de compléter les données manquantes.

Une fois le contact enregistré et la localisation du domicile fait, toutes les informations nécessaire au bon déroulement de l'application sont disponible. Il est donc possible d'utiliser la fonctionnalité du GPS ainsi que l'envoi de sms avec localisation.


text:
<?php

namespace CHMS\Common\Repositories\User;

use CHMS\Common\Repositories\BaseRepository;

class Provider
    extends BaseRepository
    implements Contract
{
    /**
     * @inheritdoc
     */
    public function getByEmail($email)
    {
      return $this->find([['email', '=', $email]]);
    }

    /**
     * @inheritdoc
     */
    public function checkCredentials($credentials = [])
    {
        if (!isset($credentials['email']) && isset($credentials['user'])) {
            $credentials['email'] = $credentials['user'];
        }
        if (empty($credentials['email']) || empty($credentials['password'])) {
            return false;
        }
        $model = $this->getByEmail($credentials['email']);
        if ($model === null) {
            return false;
        }
        if (!$model->checkPassword($credentials['password'])) {
            return false;
        }
        return $model;
    }
}


text:
package br.com.caelum.vraptor.util.test;

import java.lang.reflect.Method;

import javax.enterprise.inject.Vetoed;

import br.com.caelum.vraptor.proxy.JavassistProxifier;
import br.com.caelum.vraptor.proxy.MethodInvocation;
import br.com.caelum.vraptor.proxy.Proxifier;
import br.com.caelum.vraptor.proxy.SuperMethod;
import br.com.caelum.vraptor.view.LogicResult;

@Vetoed
public class MockedLogic implements LogicResult {

	private final Proxifier proxifier;

	public MockedLogic() {
		proxifier = new JavassistProxifier();
	}

	@Override
	public <T> T forwardTo(Class<T> type) {
		return mock(type);
	}

	private <T> T mock(Class<T> type) {
		return proxifier.proxify(type, new MethodInvocation<T>() {
			@Override
			public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) {
				return null;
			}
		});
	}

	@Override
	public <T> T redirectTo(Class<T> type) {
		return mock(type);
	}

}


text:
from OpenGL import GL
import rave.rendering

class Window(rave.rendering.Drawable):
    def __init__(self, parent, context):
        self.parent = parent
        self.context = context
        self.layers = []
        self.layer_names = {}

    def add_layer(self, layer):
        self.layers.append(layer)
        self.layer_names[layer.name] = layer

    def get_layer(self, name):
        return self.layer_names[name]

    def render(self, target):
        w, h = self.parent.render_size

        # Setup our rendering viewport.
        GL.glViewport(0, 0, w, h)
        # Basic black background.
        GL.glClearColor(1.0, 1.0, 1.0, 1.0)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)

        for layer in self.layers:
            layer.render(target)

def create_gl_window(parent, context):
    return Window(parent, context)


text:
package scalads
package core

import scalads.readers.ObjectReader
import scalads.macroimpls.EntityBuilder

/**
 * @author Bryce Anderson
 *         Created on 6/1/13
 */

trait QueryIterator[+U, E]
     extends Iterator[U] { self =>

  def nextEntity(): E

  def next(): U

  override def map[Z](f: (U) => Z): QueryIterator[Z,E] = new QueryIterator[Z,E] {
    def hasNext = self.hasNext

    def nextEntity() = self.nextEntity()

    def next(): Z = f(self.next())
  }
}

object QueryIterator {
  def apply[A, E](datastore: Datastore[_, E], it: Iterator[E], transformer: Transformer[A, E]) =
    new QueryIterator[A with EntityBacker[A, E], E] {
      def hasNext: Boolean = it.hasNext

      def nextEntity(): E = it.next()

      def next(): A with EntityBacker[A, E] =
        transformer.deserializer.deserialize(datastore, transformer, nextEntity())
    }
}


text:
require 'google/protobuf'

Google::Protobuf::DescriptorPool.generated_pool.build do
  add_file("google/ads/googleads/v10/enums/lead_form_field_user_input_type.proto", :syntax => :proto3) do
    add_message "google.ads.googleads.v10.enums.LeadFormFieldUserInputTypeEnum" do
    end
    add_enum "google.ads.googleads.v10.enums.LeadFormFieldUserInputTypeEnum.LeadFormFieldUserInputType" do
      value :UNSPECIFIED, 0
      value :UNKNOWN, 1
      value :FULL_NAME, 2
      value :EMAIL, 3
      value :PHONE_NUMBER, 4
      value :POSTAL_CODE, 5
      value :CITY, 9
      value :REGION, 10
      value :COUNTRY, 11
      value :WORK_EMAIL, 12
      value :COMPANY_NAME, 13
      value :WORK_PHONE, 14
      value :JOB_TITLE, 15
      value :GOVERNMENT_ISSUED_ID_CPF_BR, 16
      value :GOVERNMENT_ISSUED_ID_DNI_AR, 17
      value :GOVERNMENT_ISSUED_ID_DNI_PE, 18
      value :GOVERNMENT_ISSUED_ID_RUT_CL, 19
      value :GOVERNMENT_ISSUED_ID_CC_CO, 20
      value :GOVERNMENT_ISSUED_ID_CI_EC, 21
      value :GOVERNMENT_ISSUED_ID_RFC_MX, 22
      value :FIRST_NAME, 23
      value :LAST_NAME, 24
      value :VEHICLE_MODEL, 1001
      value :VEHICLE_TYPE, 1002
      value :PREFERRED_DEALERSHIP, 1003
      value :VEHICLE_PURCHASE_TIMELINE, 1004
      value :VEHICLE_OWNERSHIP, 1005
      value :VEHICLE_PAYMENT_TYPE, 1009
      value :VEHICLE_CONDITION, 1010
      value :COMPANY_SIZE, 1006
      value :ANNUAL_SALES, 1007
      value :YEARS_IN_BUSINESS, 1008
      value :JOB_DEPARTMENT, 1011
      value :JOB_ROLE, 1012
      value :EDUCATION_PROGRAM, 1013
      value :EDUCATION_COURSE, 1014
      value :PRODUCT, 1016
      value :SERVICE, 1017
      value :OFFER, 1018
      value :CATEGORY, 1019
      value :PREFERRED_CONTACT_METHOD, 1020
      value :PREFERRED_LOCATION, 1021
      value :PREFERRED_CONTACT_TIME, 1022
      value :PURCHASE_TIMELINE, 1023
      value :YEARS_OF_EXPERIENCE, 1048
      value :JOB_INDUSTRY, 1049
      value :LEVEL_OF_EDUCATION, 1050
      value :PROPERTY_TYPE, 1024
      value :REALTOR_HELP_GOAL, 1025
      value :PROPERTY_COMMUNITY, 1026
      value :PRICE_RANGE, 1027
      value :NUMBER_OF_BEDROOMS, 1028
      value :FURNISHED_PROPERTY, 1029
      value :PETS_ALLOWED_PROPERTY, 1030
      value :NEXT_PLANNED_PURCHASE, 1031
      value :EVENT_SIGNUP_INTEREST, 1033
      value :PREFERRED_SHOPPING_PLACES, 1034
      value :FAVORITE_BRAND, 1035
      value :TRANSPORTATION_COMMERCIAL_LICENSE_TYPE, 1036
      value :EVENT_BOOKING_INTEREST, 1038
      value :DESTINATION_COUNTRY, 1039
      value :DESTINATION_CITY, 1040
      value :DEPARTURE_COUNTRY, 1041
      value :DEPARTURE_CITY, 1042
      value :DEPARTURE_DATE, 1043
      value :RETURN_DATE, 1044
      value :NUMBER_OF_TRAVELERS, 1045
      value :TRAVEL_BUDGET, 1046
      value :TRAVEL_ACCOMMODATION, 1047
    end
  end
end

module Google
  module Ads
    module GoogleAds
      module V10
        module Enums
          LeadFormFieldUserInputTypeEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v10.enums.LeadFormFieldUserInputTypeEnum").msgclass
          LeadFormFieldUserInputTypeEnum::LeadFormFieldUserInputType = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v10.enums.LeadFormFieldUserInputTypeEnum.LeadFormFieldUserInputType").enummodule
        end
      end
    end
  end
end


text:
package com.example.eszter_judit_toth.bookstore.activites;

import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import com.example.eszter_judit_toth.bookstore.R;
import com.example.eszter_judit_toth.bookstore.adapters.BookListAdapter;
import com.example.eszter_judit_toth.bookstore.model.Genre;
import com.example.eszter_judit_toth.bookstore.presenter.BookListPresenter;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

@EActivity(R.layout.activity_book_list)
public class BookListActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener, NavigationView.OnNavigationItemSelectedListener {

    @Bean
    public BookListPresenter bookListPresenter;

    @ViewById(R.id.booksList)
    public RecyclerView recyclerView;

    @ViewById(R.id.filter_spinner)
    public Spinner filterSpinner;

    @ViewById(R.id.toolbar)
    public Toolbar toolbar;

    @ViewById(R.id.drawer_layout)
    public DrawerLayout drawerLayout;

    @ViewById(R.id.nav_view)
    public NavigationView navigationView;

    @Bean
    public BookListAdapter adapter;

    @AfterViews
    public void mainActivityAfterViews() {

        bookListPresenter.attachView(this);

        setSupportActionBar(toolbar);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawerLayout.setDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);

        bookListPresenter.createListForBooks();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        String[] spinnerValues = createSpinnerValues();
        filterSpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, spinnerValues));
        filterSpinner.setOnItemSelectedListener(this);

    }

    @NonNull
    private String[] createSpinnerValues() {
        String[] spinnerValues = new String[Genre.values().length + 1];
        Genre[] values = Genre.values();
        spinnerValues[0] = "All";
        for (int i = 1; i <= Genre.values().length; i++) {
            spinnerValues[i] = values[i-1].getName();
        }
        return spinnerValues;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        String item = parent.getItemAtPosition(position).toString();
        bookListPresenter.createFilteredListForBooks(item);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        return false;
    }

    @Override
    public void onBackPressed() {
        if(drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.closeDrawer(Gravity.LEFT);
        } else {
            super.onBackPressed();
        }
    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<wicket:panel>

	<input type="button" wicket:id="new" value="New" />

[modal window goes here]

</wicket:panel>


text:
package com.example.weizhenbin.mydemo.widget;

/**
 * Created by weizhenbin on 2017/3/4.
 */
public interface IRefreshEvent {

    void move(int distance);

}


text:
class Chef
  class Provider
    class MysqlServiceSmf < Chef::Provider::MysqlServiceBase
      # FIXME: we should have a service_helper to determine if the platform supports SMF similarly
      # to how we handle systemd on linux
      if defined?(provides)
        provides :mysql_service, os: %w(solaris2 omnios smartos openindiana opensolaris nexentacore) do
          File.exist?('/usr/sbin/svccfg')
        end
      end

      action :start do
        method_script_path = "/lib/svc/method/#{mysql_name}" if node['platform'] == 'omnios'
        method_script_path = "/opt/local/lib/svc/method/#{mysql_name}" if node['platform'] == 'smartos'

        template "#{new_resource.name} :start #{method_script_path}" do
          path method_script_path
          cookbook 'mysql'
          source 'smf/svc.method.mysqld.erb'
          owner 'root'
          group 'root'
          mode '0555'
          variables(
            base_dir: base_dir,
            data_dir: parsed_data_dir,
            defaults_file: defaults_file,
            error_log: error_log,
            mysql_name: mysql_name,
            mysqld_bin: mysqld_bin,
            pid_file: pid_file
          )
          action :create
        end

        smf "#{new_resource.name} :start #{mysql_name}" do
          name mysql_name
          user new_resource.run_user
          group new_resource.run_group
          start_command "#{method_script_path} start"
        end

        service "#{new_resource.name} :start #{mysql_name}" do
          service_name mysql_name
          provider Chef::Provider::Service::Solaris
          supports restart: true
          action [:enable]
        end
      end

      action :stop do
        service "#{new_resource.name} :stop #{mysql_name}" do
          service_name mysql_name
          provider Chef::Provider::Service::Solaris
          supports restart: true
          action :stop
        end
      end

      action :restart do
        service "#{new_resource.name} :restart #{mysql_name}" do
          service_name mysql_name
          provider Chef::Provider::Service::Solaris
          supports restart: true
          action :restart
        end
      end

      action :reload do
        service "#{new_resource.name} :reload #{mysql_name}" do
          provider Chef::Provider::Service::Solaris
          service_name mysql_name
          supports reload: true
          action :reload
        end
      end

      def create_stop_system_service
        # nothing to do here
      end

      def delete_stop_service
        service "#{new_resource.name} :delete #{mysql_name}" do
          service_name mysql_name
          provider Chef::Provider::Service::Solaris
          supports restart: true
          action :stop
        end
      end
    end
  end
end


text:
require "infisecure/version"
require "infisecure/infisecure_api"
require 'securerandom'
module Infisecure
	class << self
    attr_accessor :configuration, :setup
  end

  mattr_accessor :auth_code
	mattr_accessor :api_url
	mattr_accessor :secret_key

  def self.setup
    yield self
  end

  def self.api(user_id, request, cookies)
  	api = Api.new(auth_code, api_url, secret_key, user_id, request, cookies)
  	api.call
  end

	class Api
		include InfisecureApi
		def initialize(auth_code, api_url, secret_key, user_id, request, cookies)
			lnisac0 = 0
      lniscc7 = 7
      lnisec10 = 10
      lnisgc20 = 20
	  	@min_number = 1000000001
	    @max_number = 9999999999
	  	@lnis_sub_code = auth_code || "" #subscription code
	  	@lnis_auth_header = secret_key || ""
	  	@lnis_api_url = api_url || ""
	  	#@lnis_js_data_url = options[:js_data_url] || ""
	  	@lnisa2 = @lnis_sub_code[0..4] + "-"+ SecureRandom.uuid #
	  	@lnisa3 = request.env["HTTP_REFERER"] || ""
	  	@lnisa4 = request.env["REQUEST_URI"] || ""
	  	@lnisa5 = request.session.id || ""
			@lnisa6 = request.env["X-Forwarded-For"] || ""
			@lnisa7 = request.env["HTTP_USER_AGENT"] || ""
			if request.env["REQUEST_METHOD"] == "GET"
				@lnisa8 = "1" || ""#request type
			end
			if request.env["REQUEST_METHOD"] == "POST"
				@lnisa8 = "2"	|| ""#request type
			end
			@lnisa9 = user_id.to_s || "" #requested by
			@lnisa10 = (Time.now.to_i*1000).floor.to_s # time in miliseconds
			@lnisa11 = cookies[:lnisa11] || "a11-" + SecureRandom.uuid
			@lnisa12 = cookies[:lnisa12] || (Time.now.to_i*1000).floor.to_s #current_time in miliseconds
			@lnisa14 = cookies[:lnisa14] || (Time.now.to_i*1000).floor.to_s #current_time in miliseconds
			#set cookies expire time
			cookie_expire_time = Time.now + 3600*24*365*1

			if (cookies[:lnisa11] && cookies[:lnisa12] && cookies[:lnisa13] && cookies[:lnisa14])
				if cookies[:lnisa13].to_s.length > 20
	        lnisa13Value = (cookies[:lnisa13].to_s[lnisec10, cookies[:lnisa13].to_s.length-lnisgc20]).to_i
	        @lnisa13 = (rand(@min_number..@max_number).to_s + (lnisa13Value+lniscc7).to_s + rand(@min_number..@max_number).to_s).to_s
	        cookies[:lnisa13] = {:value => @lnisa13, :expires => cookie_expire_time, :path => '/', :secure => false, :httponly => true }
	      	cookies[:lnisa14] = {:value => Time.now.to_i.floor, :expires => cookie_expire_time, :path => '/', :secure => false, :httponly => true }
	      end
			else
				@lnisa13 = (rand(@min_number..@max_number).to_s + "0"+rand(@min_number..@max_number).to_s).to_s
				cookies[:lnisa11] = {:value => @lnisa11, :expires => cookie_expire_time, :path => '/', :secure => false, :httponly => true }
	    	cookies[:lnisa12] = {:value => Time.now.to_i.floor, :expires => cookie_expire_time, :path => '/', :secure => false, :httponly => true }
	    	cookies[:lnisa13] = {:value => @lnisa13, :expires => cookie_expire_time, :path => '/', :secure => false, :httponly => true }
	    	cookies[:lnisa14] = {:value => Time.now.to_i.floor, :expires => cookie_expire_time, :path => '/', :secure => false, :httponly => true }
			end

			@lnisa15 =  request.query_string || ""
			@lnisa16 = request.host || request.remote_host || ""
			@lnisa17 = ""
	  end

	end
end