text:
package org.apache.hadoop.hbase.io;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.TreeMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import junit.framework.TestCase;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.SmallTests;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.hfile.BlockCacheKey;
import org.apache.hadoop.hbase.io.hfile.CachedBlock;
import org.apache.hadoop.hbase.io.hfile.LruBlockCache;
import org.apache.hadoop.hbase.regionserver.HRegion;
import org.apache.hadoop.hbase.regionserver.MemStore;
import org.apache.hadoop.hbase.regionserver.HStore;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.util.ClassSize;
import org.junit.experimental.categories.Category;
import org.junit.BeforeClass;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;

/**
 * Testing the sizing that HeapSize offers and compares to the size given by
 * ClassSize.
 */
@Category(SmallTests.class)
public class TestHeapSize extends TestCase {
  static final Log LOG = LogFactory.getLog(TestHeapSize.class);
  // List of classes implementing HeapSize
  // BatchOperation, BatchUpdate, BlockIndex, Entry, Entry<K,V>, HStoreKey
  // KeyValue, LruBlockCache, LruHashMap<K,V>, Put, HLogKey

  @BeforeClass
  public void beforeClass() throws Exception {
    // Print detail on jvm so we know what is different should below test fail.
    RuntimeMXBean b = ManagementFactory.getRuntimeMXBean();
    LOG.info("name=" + b.getName());
    LOG.info("specname=" + b.getSpecName());
    LOG.info("specvendor=" + b.getSpecVendor());
    LOG.info("vmname=" + b.getVmName());
    LOG.info("vmversion=" + b.getVmVersion());
    LOG.info("vmvendor=" + b.getVmVendor());
    Map<String, String> p = b.getSystemProperties();
    LOG.info("properties=" + p);
  }

  /**
   * Test our hard-coded sizing of native java objects
   */
  public void testNativeSizes() throws IOException {
    @SuppressWarnings("rawtypes")
    Class cl = null;
    long expected = 0L;
    long actual = 0L;

    // ArrayList
    cl = ArrayList.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.ARRAYLIST;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // ByteBuffer
    cl = ByteBuffer.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.BYTE_BUFFER;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // Integer
    cl = Integer.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.INTEGER;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // Map.Entry
    // Interface is public, all others are not.  Hard to size via ClassSize
//    cl = Map.Entry.class;
//    expected = ClassSize.estimateBase(cl, false);
//    actual = ClassSize.MAP_ENTRY;
//    if(expected != actual) {
//      ClassSize.estimateBase(cl, true);
//      assertEquals(expected, actual);
//    }

    // Object
    cl = Object.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.OBJECT;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // TreeMap
    cl = TreeMap.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.TREEMAP;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // String
    cl = String.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.STRING;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // ConcurrentHashMap
    cl = ConcurrentHashMap.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.CONCURRENT_HASHMAP;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // ConcurrentSkipListMap
    cl = ConcurrentSkipListMap.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.CONCURRENT_SKIPLISTMAP;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // ReentrantReadWriteLock
    cl = ReentrantReadWriteLock.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.REENTRANT_LOCK;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // AtomicLong
    cl = AtomicLong.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.ATOMIC_LONG;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // AtomicInteger
    cl = AtomicInteger.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.ATOMIC_INTEGER;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // AtomicBoolean
    cl = AtomicBoolean.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.ATOMIC_BOOLEAN;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // CopyOnWriteArraySet
    cl = CopyOnWriteArraySet.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.COPYONWRITE_ARRAYSET;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // CopyOnWriteArrayList
    cl = CopyOnWriteArrayList.class;
    expected = ClassSize.estimateBase(cl, false);
    actual = ClassSize.COPYONWRITE_ARRAYLIST;
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

  }

  /**
   * Testing the classes that implements HeapSize and are a part of 0.20.
   * Some are not tested here for example BlockIndex which is tested in
   * TestHFile since it is a non public class
   * @throws IOException
   */
  public void testSizes() throws IOException {
    @SuppressWarnings("rawtypes")
    Class cl = null;
    long expected = 0L;
    long actual = 0L;

    //KeyValue
    cl = KeyValue.class;
    expected = ClassSize.estimateBase(cl, false);
    KeyValue kv = new KeyValue();
    actual = kv.heapSize();
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    //Put
    cl = Put.class;
    expected = ClassSize.estimateBase(cl, false);
    //The actual TreeMap is not included in the above calculation
    expected += ClassSize.TREEMAP;
    Put put = new Put(Bytes.toBytes(""));
    actual = put.heapSize();
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    //LruBlockCache Overhead
    cl = LruBlockCache.class;
    actual = LruBlockCache.CACHE_FIXED_OVERHEAD;
    expected = ClassSize.estimateBase(cl, false);
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // CachedBlock Fixed Overhead
    // We really need "deep" sizing but ClassSize does not do this.
    // Perhaps we should do all these more in this style....
    cl = CachedBlock.class;
    actual = CachedBlock.PER_BLOCK_OVERHEAD;
    expected = ClassSize.estimateBase(cl, false);
    expected += ClassSize.estimateBase(String.class, false);
    expected += ClassSize.estimateBase(ByteBuffer.class, false);
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      ClassSize.estimateBase(String.class, true);
      ClassSize.estimateBase(ByteBuffer.class, true);
      assertEquals(expected, actual);
    }

    // MemStore Overhead
    cl = MemStore.class;
    actual = MemStore.FIXED_OVERHEAD;
    expected = ClassSize.estimateBase(cl, false);
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // MemStore Deep Overhead
    actual = MemStore.DEEP_OVERHEAD;
    expected = ClassSize.estimateBase(cl, false);
    expected += ClassSize.estimateBase(ReentrantReadWriteLock.class, false);
    expected += ClassSize.estimateBase(AtomicLong.class, false);
    expected += ClassSize.estimateBase(ConcurrentSkipListMap.class, false);
    expected += ClassSize.estimateBase(ConcurrentSkipListMap.class, false);
    expected += ClassSize.estimateBase(CopyOnWriteArraySet.class, false);
    expected += ClassSize.estimateBase(CopyOnWriteArrayList.class, false);
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      ClassSize.estimateBase(ReentrantReadWriteLock.class, true);
      ClassSize.estimateBase(AtomicLong.class, true);
      ClassSize.estimateBase(ConcurrentSkipListMap.class, true);
      ClassSize.estimateBase(CopyOnWriteArraySet.class, true);
      ClassSize.estimateBase(CopyOnWriteArrayList.class, true);
      assertEquals(expected, actual);
    }

    // Store Overhead
    cl = HStore.class;
    actual = HStore.FIXED_OVERHEAD;
    expected = ClassSize.estimateBase(cl, false);
    if(expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // Region Overhead
    cl = HRegion.class;
    actual = HRegion.FIXED_OVERHEAD;
    expected = ClassSize.estimateBase(cl, false);
    if (expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // Block cache key overhead
    cl = BlockCacheKey.class;
    // Passing zero length file name, because estimateBase does not handle
    // deep overhead.
    actual = new BlockCacheKey("", 0).heapSize();
    expected  = ClassSize.estimateBase(cl, false);
    if (expected != actual) {
      ClassSize.estimateBase(cl, true);
      assertEquals(expected, actual);
    }

    // Currently NOT testing Deep Overheads of many of these classes.
    // Deep overheads cover a vast majority of stuff, but will not be 100%
    // accurate because it's unclear when we're referencing stuff that's already
    // accounted for.  But we have satisfied our two core requirements.
    // Sizing is quite accurate now, and our tests will throw errors if
    // any of these classes are modified without updating overhead sizes.
  }

}


text:
Ce projet permet de se créer un compte, de gérer les sessions, les amis etc.
Il utilise FOSuserbundle pour la géstion des utilisateurs.
Responsive design avec Bootstrap.

# Installation
## 1. Récupération du code
- Par clonage du dépot

    ou

- En téléchargeant l'archive .ZIP

## 2. Installer les vendors
Utiliser composer :

####Le mettre à jour
=====================

**Unix** :
```
php composer.phar update
```
**Windows** :
```
composer update
```

--------------------------
####Installer
=====================

**Unix** :
```shell
    php composer.phar install
```

**Windows** :
```
    composer install
 ```
 (voir https://getcomposer.org/download/)
 --------------------------

 /!\ FOS\UserBundle\Form\Type\RegistrationFormType.php doit contenir dans le buildForm

```php
->add('race', TextType::class)
->add('age', TextType::class)
->add('nourriture', ChoiceType::class, array(
    'choices'  => array(
        'Bananes' => 'Bananes',
        'Cacahuètes' => 'Cacahuètes',
        'Pommes' => 'Pommes',
        'Fleurs' => 'Fleurs',)
        ))
```
 /!\
## 3. La base de données
```
    php bin/console doctrine:database:create
```
Puis créez les tables:
```
    php bin/console doctrine:schema:update --dump-sql
    php bin/console doctrine:schema:update --force
```

## 4. Assets
```
    php bin/console assets:install web
```

## 5. Images
![alt tag](https://github.com/TimPrd/SymfonyBonobo/blob/master/haut.png)

 Haut de l'écran

![alt tag](https://github.com/TimPrd/SymfonyBonobo/blob/master/inscription.png)

 Inscription

redpajama_set_name: RedPajamaGithub


text:
//
//  VFRFormValidator.h
//
//  Copyright (c) 2014 Joseph Lorich.
//

#import <Foundation/Foundation.h>
#import "VFRValidatedTextField.h"

/**
 * A form field validator
 */
@interface VFRFormValidator : NSObject

#pragma mark - Properties

/// The fields tied to this validator
@property (nonatomic) NSMutableArray *fields;

/// Whether or not the form is currently valid (triggers validation)
@property (readonly) BOOL valid;

/// A combined error message for this form
@property NSString *errorMessage;

#pragma mark - Methods

/**
 * Inits a validator for a set of fields
 */
- (id)initWithFields:(VFRValidatedTextField *)textField1,... NS_REQUIRES_NIL_TERMINATION;

/**
 * Creates a form validator based on a set of fields
 */
+ (VFRFormValidator *)formValidatorWithFields:(VFRValidatedTextField *)textField1,... NS_REQUIRES_NIL_TERMINATION;

/**
 * Check validity on all form fields
 */
- (BOOL) validate;

/**
 * Adds a general block validator
 */
//- (void)addBlockValidator:(ValidationBlock)block;

@end


text:
function show_submenu(obj){
	var menu_links = $$('.toplevel li a');
	for(i=0;i<menu_links.length;i++) {
		if(menu_links[i].className=='current'){
			menu_links[i].className='';
		}
	}
	var submenus = $$('.secondlevel');
	for(i=0;i<submenus.length;i++) {
	      if(submenus[i].style.display=='block'){
			  submenus[i].hide();
		  }
	}
	obj.className='current';
	var current_submenu ;
	current_submenu = obj.nextSiblings();
	current_submenu[0].style.display="block";
	current_submenu[0].fade({duration: 0.5,from: 0.5, to: 1});
}

function switch_help_content(){
	var c = new Cookies();
	if($('switch_help_content_btn').className=='btn_min'){
		control_help_content("hide");
		c.set('help_form','hidden');
	}else{
		control_help_content("show");
		c.set('help_form','shown');
	}
}

function init_help_content(){
	var c = new Cookies();
	status = c.get('help_form');
	switch(status){
		case 'shown':
			control_help_content("show");
			break;
		case 'hidden':
		default:
			control_help_content("hide");
			break;

	}
}

function control_help_content(action){
	switch(action){
		case "hide":
			$('help_content').style.display="none";
			$('switch_help_content_btn').className='btn_max';
			break;
		case "show":
			default:
			$('help_content').style.display="block";
			$('help_content').fade({duration: 0.5,from: 0.5, to: 1});
			$('switch_help_content_btn').className='btn_min';
			setTimeout("$('help_content').show();",600);
			break;
	}
}

function top_menu_move(){
	var c = new Cookies();
	top_menu_first=parseInt(top_menu_first);
	switch(top_menu_move_direction){
		case 'left':
			if(top_menu_first>0){
				top_menu_first=top_menu_first-1;
			}
			break;
		case 'right':
			if(top_menu_first<(top_menu_count-5)){
				top_menu_first=top_menu_first+1;
			}
			break;
	}
	pos=0-top_menu_first*top_menu_item_width ;
	c.set('top_menu_first',top_menu_first);
	new Effect.Move($('top_menu_list'), { x: pos, y: 0, mode: 'absolute' });
}

function init_top_menu_pos(){
	var c = new Cookies();
	if(c.get('top_menu_first')){
		top_menu_first=c.get('top_menu_first');
	}
	$('menu').style.position='relative';
	$('top_menu_list').style.position='relative';
	pos = (0-top_menu_first*top_menu_item_width);
	$('top_menu_list').style.left=pos+'px';
	try{
		$('top_menu_list').style.paddingLeft=pos+'px';
	}catch(e){}
	new Effect.Move($('top_menu_list'), { x: pos, y: 0, mode: 'absolute' });
	top_menu_play_daemon();
}

function top_menu_play_daemon(){
	if(top_menu_play==true){
		top_menu_move();
	}
	setTimeout("top_menu_play_daemon()",top_menu_play_speed);
}

window.onload=fade_loader;

function fade_loader(){
	window.setTimeout("$('main_loader').fade( {from: 0.7, to: 0});",800);
	window.setTimeout("$('main_loader_bg').fade( {from: 0.7, to: 0});",800);
	window.setTimeout("$('main_loader').hide();",1000);
	window.setTimeout("$('main_loader_bg').hide();",1000);
	window.setTimeout("$('main_loader_bg').style.height='0px';",1500);
}

function show_loader(){
	$('main_loader').show();
	$('main_loader_bg').show();
	$('main_loader_bg').style.height='1000px';
	$('main_loader_bg').style.display='block';
}

function toggleDisplay(id){
	if($(id).style.display=='none'){
		$(id).show();
		$(id+"_toggler").className='shrink';
	}else{
		$(id).hide();
		$(id+"_toggler").className='expand';
	}
}

function init_elementset(formName,id)
{
	var c = new Cookies();
	status = c.get(formName+"_"+id);
	switch(status){
		default:
		case 'shown':
			control_elementset(formName,id,'show');
			break;
		case 'hidden':
			control_elementset(formName,id,'hide');
			break;

	}
}

function switch_elementset(formName,id)
{
	var c = new Cookies();
	if($('element_set_btn_'+id).className=='shrink'){
		control_elementset(formName,id,"hide");
		c.set(formName+"_"+id,'hidden');
	}else{
		control_elementset(formName,id,"show");
		c.set(formName+"_"+id,'shown');
	}
}

function control_elementset(formName,id,action)
{
	switch(action){
	case "hide":
		$('element_set_panel_'+id).style.position="absolute";
		$('element_set_panel_'+id).style.left="-10000px";
		$('element_set_btn_'+id).className='expand';
		break;
	case "show":
		default:
		if($('element_set_panel_'+id).style.position=="absolute"){
			$('element_set_panel_'+id).style.position="static";
			$('element_set_panel_'+id).style.left="";
			$('element_set_panel_'+id).fade({duration: 0.5,from: 0.5, to: 1});
			$('element_set_btn_'+id).className='shrink';
		}
		break;
	}
}


text:
@interface UIViewController(Metrics)

@property (nonatomic, readonly) CGRect		frame;
@property (nonatomic, readonly) CGRect		bounds;
@property (nonatomic, readonly) CGSize		size;
@property (nonatomic, readonly) CGFloat		width;
@property (nonatomic, readonly) CGFloat		height;

@property (nonatomic, readonly) CGRect		viewFrame;
@property (nonatomic, readonly) CGRect		viewBound;
@property (nonatomic, readonly) CGSize		viewSize;
@property (nonatomic, readonly) CGFloat		viewWidth;
@property (nonatomic, readonly) CGFloat		viewHeight;

@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Text;
using System.Xml.Serialization;
using System.Xml;
using NPOI.OpenXml4Net.Util;
using System.IO;

namespace NPOI.OpenXmlFormats.Spreadsheet
{
    /// <summary>
    /// Holds the Column Width and its Formatting
    /// </summary>
    [Serializable]
    [XmlType(Namespace = "http://schemas.openxmlformats.org/spreadsheetml/2006/main")]
    public class CT_Col
    {

        private uint minField; // required

        private uint maxField; // required

        private double widthField;  // optional, but width has no default value
        private bool widthSpecifiedField;

        private uint styleField;// optional, as are the following attributes
        private bool styleSpecifiedField;

        private bool hiddenField;

        private bool bestFitField;

        private bool customWidthField;

        private bool phoneticField;

        private byte outlineLevelField;

        private bool collapsedField = true;
        private bool collapsedSpecifiedField = true;

        [XmlAttribute]
        public uint min
        {
            get
            {
                return this.minField;
            }
            set
            {
                this.minField = value;
            }
        }

        [XmlAttribute]
        public uint max
        {
            get
            {
                return this.maxField;
            }
            set
            {
                this.maxField = value;
            }
        }

        [XmlAttribute]
        public double width
        {
            get
            {
                return this.widthField;
            }
            set
            {
                this.widthField = value;
                this.widthSpecified = true;
            }
        }
        [XmlIgnore]
        public bool widthSpecified
        {
            get
            {
                return this.widthSpecifiedField;
            }
            set
            {
                this.widthSpecifiedField = value;
            }
        }

        public bool IsSetBestFit()
        {
            return this.bestFitField != false;
        }
        public bool IsSetCustomWidth()
        {
            return this.customWidthField != false;
        }
        public bool IsSetHidden()
        {
            return this.hiddenField != false;
        }
        public bool IsSetStyle()
        {
            return this.styleField!=null;
        }
        public bool IsSetWidth()
        {
            return this.widthField>0;
        }
        public bool IsSetCollapsed()
        {
            return this.collapsedSpecifiedField;
        }
        public bool IsSetPhonetic()
        {
            return this.phoneticField != false;
        }
        public bool IsSetOutlineLevel()
        {
            return this.outlineLevelField != 0;
        }
        public void UnsetHidden()
        {
            this.hiddenField = false;
        }
        public void UnsetCollapsed()
        {
            this.collapsedField = true;
            this.collapsedSpecified = false;
        }

        [DefaultValue(typeof(uint), "0")]
        [XmlAttribute]
        public uint style
        {
            get
            {
                return styleField;
            }
            set
            {
                this.styleField = value;
            }
        }
        [XmlIgnore]
        public bool styleSpecified
        {
            get { return this.styleSpecifiedField; }
            set { this.styleSpecifiedField = value; }
        }

        [DefaultValue(false)]
        [XmlAttribute]
        public bool hidden
        {
            get
            {
                return hiddenField;
            }
            set
            {
                this.hiddenField = value;
            }
        }

        [DefaultValue(false)]
        [XmlAttribute]
        public bool bestFit
        {
            get
            {
                return bestFitField;
            }
            set
            {
                this.bestFitField = value;
            }
        }
        [DefaultValue(false)]
        [XmlAttribute]
        public bool customWidth
        {
            get
            {
                return customWidthField;
            }
            set
            {
                this.customWidthField = value;
            }
        }

        [DefaultValue(false)]
        [XmlAttribute]
        public bool phonetic
        {
            get
            {
                return phoneticField;
            }
            set
            {
                this.phoneticField = value;
            }
        }

        [DefaultValue(typeof(byte), "0")]
        [XmlAttribute]
        public byte outlineLevel
        {
            get
            {
                return outlineLevelField;
            }
            set
            {
                this.outlineLevelField = value;
            }
        }

        [DefaultValue(true)]
        [XmlAttribute]
        public bool collapsed
        {
            get
            {
                return collapsedField;
            }
            set
            {
                this.collapsedField = value;
                this.collapsedSpecifiedField = true;
            }
        }
        [XmlIgnore]
        public bool collapsedSpecified
        {
            get { return this.collapsedSpecifiedField; }
            set { this.collapsedSpecifiedField = value; }
        }

        public CT_Col()
        {

        }

        public static CT_Col Parse(XmlNode node, XmlNamespaceManager namespaceManager)
        {
            if (node == null)
                return null;
            CT_Col ctObj = new CT_Col();
            ctObj.min = XmlHelper.ReadUInt(node.Attributes["min"]);
            ctObj.max = XmlHelper.ReadUInt(node.Attributes["max"]);
            ctObj.width = XmlHelper.ReadDouble(node.Attributes["width"]);
            ctObj.style = XmlHelper.ReadUInt(node.Attributes["style"]);
            ctObj.hidden = XmlHelper.ReadBool(node.Attributes["hidden"]);
            ctObj.bestFit = XmlHelper.ReadBool(node.Attributes["bestFit"]);
            ctObj.outlineLevel = XmlHelper.ReadByte(node.Attributes["outlineLevel"]);
            ctObj.customWidth = XmlHelper.ReadBool(node.Attributes["customWidth"]);
            ctObj.phonetic = XmlHelper.ReadBool(node.Attributes["phonetic"]);
            ctObj.collapsed = XmlHelper.ReadBool(node.Attributes["collapsed"]);
            return ctObj;
        }

        internal void Write(StreamWriter sw, string nodeName)
        {
            sw.Write(string.Format("<{0}", nodeName));
            XmlHelper.WriteAttribute(sw, "min", this.min);
            XmlHelper.WriteAttribute(sw, "max", this.max);
            XmlHelper.WriteAttribute(sw, "width", this.width);
            XmlHelper.WriteAttribute(sw, "style", this.style,true);
            XmlHelper.WriteAttribute(sw, "hidden", this.hidden,false);
            XmlHelper.WriteAttribute(sw, "bestFit", this.bestFit,false);
            XmlHelper.WriteAttribute(sw, "customWidth", this.customWidth,false);
            XmlHelper.WriteAttribute(sw, "phonetic", this.phonetic,false);
            XmlHelper.WriteAttribute(sw, "outlineLevel", this.outlineLevel);
            XmlHelper.WriteAttribute(sw, "collapsed", this.collapsed,false);
            sw.Write("/>");
        }

    }
}


text:
package com.google.cloud.bigtable.grpc.async;

import java.util.ArrayList;
import java.util.List;

import com.google.bigtable.v2.MutateRowsRequest;
import com.google.bigtable.v2.MutateRowsResponse;
import com.google.bigtable.v2.MutateRowsResponse.Entry;
import com.google.cloud.bigtable.config.RetryOptions;
import com.google.cloud.bigtable.grpc.BigtableDataClient;
import com.google.rpc.Status;

import io.grpc.Status.Code;

/**
 * Performs retries for {@link BigtableDataClient#mutateRows(MutateRowsRequest)} operations.
 */
public class MutateRowsRequestManager  {
  private final static Status STATUS_INTERNAL =
      Status.newBuilder()
        .setCode(io.grpc.Status.Code.INTERNAL.value())
        .setMessage("Response was not returned for this index.")
        .build();

  private static Code getGrpcCode(Status status) {
    return status == null ? null : io.grpc.Status.fromCodeValue(status.getCode()).getCode();
  }

  private static Entry createEntry(int i, Status status) {
    return MutateRowsResponse.Entry.newBuilder().setIndex(i).setStatus(status).build();
  }

  public enum ProcessingStatus {
    /* All responses produced OK */
    SUCCESS,
    /* All responses produced OK or a retryable code */
    RETRYABLE,
    /* Some responses a non-retryable code */
    NOT_RETRYABLE,
    /* The response was invalid - missing indexes and etc. */
    INVALID;
  }

  /**
   * The current request to send. This starts as the original request. If retries occur, this
   * request will contain the subset of Mutations that need to be retried.
   */
  private volatile MutateRowsRequest currentRequest;

  /**
   * When doing retries, the retry sends a partial set of the original mutations that failed with a
   * retryable status. This array contains a mapping of indices from the {@link #currentRequest}
   * to {@link #originalRequest}.
   */
  private int[] mapToOriginalIndex;

  /**
   * This array tracks the cumulative set of results across all RPC requests.
   */
  private final Status[] results;
  private final RetryOptions retryOptions;
  private final MutateRowsRequest originalRequest;

  private boolean messageIsInvalid = false;

  public MutateRowsRequestManager(RetryOptions retryOptions, MutateRowsRequest originalRequest) {
    this.currentRequest = originalRequest;
    this.originalRequest = originalRequest;
    this.retryOptions = retryOptions;
    results = new Status[originalRequest.getEntriesCount()];

    // This map should is a map between currentRequest and originalRquest. For now, currentRequest
    // == originalRquest, but they could diverge if a retry occurs.
    mapToOriginalIndex = new int[originalRequest.getEntriesCount()];
    for (int i = 0; i < mapToOriginalIndex.length; i++) {
      mapToOriginalIndex[i] = i;
    }
  }

  /**
   * Adds the content of the message to the {@link #results}.
   */
  public void onMessage(MutateRowsResponse message) {
    for (Entry entry : message.getEntriesList()) {
      int index = (int) entry.getIndex();

      // Sanity check to make sure that the index returned from the server is valid.
      if (index >= mapToOriginalIndex.length || index < 0) {
        messageIsInvalid = true;
        break;
      }

      // Set the result.
      results[mapToOriginalIndex[index]] = entry.getStatus();
    }
  }

  /**
   * This is called when all calls to {@link #onMessage(MutateRowsResponse)} are complete.
   *
   * @return {@link ProcessingStatus} of the accumulated responses - success, invalid, retrable,
   *         non-retryable.
   */
  public ProcessingStatus onOK() {
    // Sanity check to make sure that every mutation received a response.
    if (!messageIsInvalid) {
      for (int i = 0; i < results.length; i++) {
        if (results[i] == null) {
          messageIsInvalid = true;
          break;
        }
      }
    }

    // There was a problem in the data found in onMessage(), so fail the RPC.
    if (messageIsInvalid) {
      return ProcessingStatus.INVALID;
    }

    List<Integer> toRetry = new ArrayList<>();
    ProcessingStatus processingStatus = ProcessingStatus.SUCCESS;

    // Check the current state to determine the state of the results.
    // There are three states: OK, Fail, or Partial Retry.
    for (int i = 0; i < results.length; i++) {
      Status status = results[i];
      if (status.getCode() == io.grpc.Status.Code.OK.value()) {
        continue;
      } else if (retryOptions.isRetryable(getGrpcCode(status))) {
        // An individual mutation failed with a retryable code, usually DEADLINE_EXCEEDED.
        toRetry.add(i);
        if (processingStatus == ProcessingStatus.SUCCESS) {
          processingStatus = ProcessingStatus.RETRYABLE;
        }
      } else {
        // Don't retry if even a single response is not retryable.
        processingStatus = ProcessingStatus.NOT_RETRYABLE;
        break;
      }
    }

    if (!toRetry.isEmpty()) {
      currentRequest = createRetryRequest(toRetry);
    }

    return processingStatus;
  }

  public MutateRowsRequest getRetryRequest() {
    return currentRequest;
  }

  /**
   * Creates a new {@link MutateRowsRequest} that's a subset of the original request that
   * corresponds to a set of indices.
   *
   * @param indiciesToRetry
   * @return the new {@link MutateRowsRequest}.
   */
  private MutateRowsRequest createRetryRequest(List<Integer> indiciesToRetry) {
    MutateRowsRequest.Builder updatedRequest = MutateRowsRequest.newBuilder()
        .setTableName(originalRequest.getTableName());
    mapToOriginalIndex = new int[indiciesToRetry.size()];
    for (int i = 0; i < indiciesToRetry.size(); i++) {
      mapToOriginalIndex[i] = indiciesToRetry.get(i);
      updatedRequest.addEntries(originalRequest.getEntries(indiciesToRetry.get(i)));
    }
    return updatedRequest.build();
  }

  /**
   * @return a {@link MutateRowsResponse} built from the accumulation of all calls to
   *         onMessage/onOK.
   */
  public MutateRowsResponse buildResponse() {
    List<MutateRowsResponse.Entry> entries = new ArrayList<>();
    for (int i = 0; i < results.length; i++) {
      Status status = (results[i] == null) ? STATUS_INTERNAL : results[i];
      entries.add(createEntry(i, status));
    }
    return MutateRowsResponse.newBuilder().addAllEntries(entries).build();
  }
}


text:
angular.module('draft').component('draft', {
  templateUrl: 'draft/draft.template.html',
  controller: ['$http', '$routeParams', function DraftController($http, $routeParams) {
    const that = this;
    this.league = null;

    $http.get(`/api/leagues/${$routeParams.leagueId}`)
      .success(function(data) {
        that.league = data;
      })
      .error(function(data) {
        console.log(`Error: ${data}`);
      });
  }]
});


text:
/**
 * Contains Query holder classes for gradoop accumulo
 */
package org.gradoop.storage.accumulo.impl.predicate.query;


text:
#import <Cocoa/Cocoa.h>
#import <SystemConfiguration/SystemConfiguration.h>
#include "AvailabilityMacros.h"
#import <SystemConfiguration/SCNetworkReachability.h>
#import <asl.h>
#import "VVCURLDL.h"
#import "MutLockArray.h"

///	The crash reporter's delegate must adhere to this protocol
/*!
	This protocol exists largely because it's conceivable that objects will want to know when the crash reporter- which uploads asynchronously- has finished sending its data to the remote server.
*/
@protocol OldVVCrashReporterDelegate
- (void) crashReporterCheckDone;
@end

@protocol VVCrashReporterDelegate
- (void) crashReporterCheckDone:(BOOL)foundLogs;	//	"new"- 'f' designates whether crash reports were found or not
- (void) crashReporterWillSendLog:(NSString *)crashString;
@end

///	Simple class which automatically uploads crash logs and other relevant diagnostic information automatically made available by os x to a remote server.
/*!
it's been my experience that most apps crash much more frequently on end-users than the app's developers would guess.  the simplest and easiest way to improve the end-user's experience is to have the application check their machine for crash logs- which are generated automatically by os x whenever an application crashes- and send them to the developer.

this class exists so i have a really easy way to make my apps send their crash logs to me; the goal here is to make it as easy as possible to get all the information i need to troubleshoot a problem with as little work on the user's part as possible.  it also sends a basic system profile, anything the app- and ONLY the app, not other apps- recently printed to the console log, and optional description/email fields to facilitate communication directly with the user.  this data is then uploaded to a given URL using an HTTP POST.

on the server side, i use a PHP page which sanitizes the POST data (i can't stress how important this step is) and works with it.  i've included a sample PHP page that simply dumps the received data to a file on disk (and optionally emails someone) with this project.

HOW TO USE THIS CLASS:

	1)- create an instance of this class

	2)- set the instance's delegate, uploadURL, and developerEmail.  these are necessary!

	3)- call "check" on the instance.  when it's done, it calls "crashReporterCheckDone" on the
		delegate.  that's it- you're done.
*/

@interface VVCrashReporter : NSObject <VVCURLDLDelegate> {
	NSString						*domainToCheck;
	NSString						*uploadURL;	//	does NOT includes http://
	NSString						*developerEmail;
	id								delegate;	//	must respond to VVCrashReporterDelegate protocol
	MutLockArray					*crashLogArray;
	NSMutableDictionary				*systemProfilerDict;
	NSString						*consoleLog;
	int								jobSize;			//	used to update progress indicator/label
	int								jobCurrentIndex;	//	used to update progress indicator/label
	int								currentCrashLogTimeout;	//	countdown for timeout of sending/receiving data for a specific crash log
	NSTimer							*currentCrashLogTimer;

	IBOutlet NSWindow				*window;
	IBOutlet NSButton				*replyButton;
	IBOutlet NSView					*emailFieldHolder;
	IBOutlet NSTextField			*emailField;
	IBOutlet NSTextView				*descriptionField;
	IBOutlet NSTextField			*submittingLabel;	//	non-editable. 'submitting', 'getting machine profile', etc.
	IBOutlet NSProgressIndicator	*progressIndicator;	//	indicates progress through all crash logs to be submitted
	IBOutlet NSTextField			*countdownLabel;	//	non-editable; countdown so user knows app hasn't hung

	NSNib							*theNib;
	NSArray							*nibTopLevelObjects;
}

+ (NSString *) _stringForSystemProfilerDataType:(NSString *)t;

///	This is the main method- when you call 'check', the crash reporter looks for crash logs, gets a basic system profile, and collects anything your applications has dumped to the console log.
- (void) check;
- (void) checkLogs;
- (void) checkServerAndLogs;
- (void) openCrashReporter;
- (IBAction) replyButtonClicked:(id)sender;
- (IBAction) doneClicked:(id)sender;
- (void) sendACrashLog;
- (void) closeCrashReporter;

- (NSString *) _nibName;
- (BOOL) _assembleCrashLogs;	//	assembles the array of crash logs, returns a YES if logs were found and have to be sent in
- (NSString *) _consoleLogString;
- (NSMutableDictionary *) _systemProfilerDict;

- (void) updateCrashLogTimeout:(NSTimer *)t;

//	VVCURLDLDelegate method- this class will be the delegate of multiple VVCURLDL instances
- (void) dlFinished:(id)h;

///	Optional.  Sets the domain to check, expects something like "vidvox.com"- if used, the domain is looked up first (pretty sure the SCNetwork stuff tries to send a UDP packet to this domain) to ensure that it exists: if it doesn't, the crash reporter window simply isn't displayed.
- (void) setDomainToCheck:(NSString *)n;
- (NSString *) domainToCheck;
///	Sets the developer email address; this is displayed if the user has a problem connecting to the internet/the server the crash reporter is supposed to be connecting to
- (void) setDeveloperEmail:(NSString *)n;
- (NSString *) developerEmail;
///	This is the URL of the php/cgi/etc. page which the crash data will be POSTed to
- (void) setUploadURL:(NSString *)n;
- (NSString *) uploadURL;

///	The crash reporter's delegate is notified when the check has completed
@property (assign,readwrite) id delegate;
@property (readonly) NSButton *replyButton;

@end


text:
package io.hgraphdb;

public enum OperationType {
    READ,
    WRITE,
    REMOVE
}


text:
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2008-2017 FIRST. All Rights Reserved.                        */
/* Open Source Software - may be modified and shared by FRC teams. The code   */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project.                                                               */
/*----------------------------------------------------------------------------*/

package edu.wpi.first.wpilibj;

import java.nio.ByteBuffer;

import edu.wpi.first.wpilibj.hal.FRCNetComm.tResourceType;
import edu.wpi.first.wpilibj.hal.HAL;
import edu.wpi.first.wpilibj.hal.I2CJNI;
import edu.wpi.first.wpilibj.util.BoundaryException;

import static java.util.Objects.requireNonNull;

/**
 * I2C bus interface class.
 *
 *
This class is intended to be used by sensor (and other I2C device) drivers. It probably should
 * not be used directly.
 */
public class I2C extends SensorBase {
  public enum Port {
    kOnboard(0), kMXP(1);

    @SuppressWarnings("MemberName")
    public final int value;

    private Port(int value) {
      this.value = value;
    }
  }

  private final int m_port;
  private final int m_deviceAddress;

  /**
   * Constructor.
   *
   * @param port          The I2C port the device is connected to.
   * @param deviceAddress The address of the device on the I2C bus.
   */
  public I2C(Port port, int deviceAddress) {
    m_port = port.value;
    m_deviceAddress = deviceAddress;

    I2CJNI.i2CInitialize((byte) port.value);

    HAL.report(tResourceType.kResourceType_I2C, deviceAddress);
  }

  /**
   * Destructor.
   */
  public void free() {
  }

  /**
   * Generic transaction.
   *
   *
This is a lower-level interface to the I2C hardware giving you more control over each
   * transaction.
   *
   * @param dataToSend   Buffer of data to send as part of the transaction.
   * @param sendSize     Number of bytes to send as part of the transaction.
   * @param dataReceived Buffer to read data into.
   * @param receiveSize  Number of bytes to read from the device.
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public synchronized boolean transaction(byte[] dataToSend, int sendSize,
                                          byte[] dataReceived, int receiveSize) {
    final int status;

    ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(sendSize);
    if (sendSize > 0 && dataToSend != null) {
      dataToSendBuffer.put(dataToSend);
    }
    ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(receiveSize);

    status = I2CJNI.i2CTransaction(m_port, (byte) m_deviceAddress, dataToSendBuffer,
                                   (byte) sendSize, dataReceivedBuffer, (byte) receiveSize);
    if (receiveSize > 0 && dataReceived != null) {
      dataReceivedBuffer.get(dataReceived);
    }
    return status < 0;
  }

  /**
   * Generic transaction.
   *
   *
This is a lower-level interface to the I2C hardware giving you more control over each
   * transaction.
   *
   * @param dataToSend   Buffer of data to send as part of the transaction. Must be allocated using
   *                     ByteBuffer.allocateDirect().
   * @param sendSize     Number of bytes to send as part of the transaction.
   * @param dataReceived Buffer to read data into. Must be allocated using {@link
   *                     ByteBuffer#allocateDirect(int)}.
   * @param receiveSize  Number of bytes to read from the device.
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public synchronized boolean transaction(ByteBuffer dataToSend, int sendSize,
                                          ByteBuffer dataReceived, int receiveSize) {
    if (!dataToSend.isDirect()) {
      throw new IllegalArgumentException("dataToSend must be a direct buffer");
    }
    if (dataToSend.capacity() < sendSize) {
      throw new IllegalArgumentException("dataToSend is too small, must be at least " + sendSize);
    }
    if (!dataReceived.isDirect()) {
      throw new IllegalArgumentException("dataReceived must be a direct buffer");
    }
    if (dataReceived.capacity() < receiveSize) {
      throw new IllegalArgumentException(
          "dataReceived is too small, must be at least " + receiveSize);
    }

    return I2CJNI.i2CTransaction(m_port, (byte) m_deviceAddress, dataToSend,
                                 (byte) sendSize, dataReceived, (byte) receiveSize) < 0;
  }

  /**
   * Attempt to address a device on the I2C bus.
   *
   *
This allows you to figure out if there is a device on the I2C bus that responds to the
   * address specified in the constructor.
   *
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public boolean addressOnly() {
    return transaction((byte[]) null, (byte) 0, null, (byte) 0);
  }

  /**
   * Execute a write transaction with the device.
   *
   *
Write a single byte to a register on a device and wait until the transaction is complete.
   *
   * @param registerAddress The address of the register on the device to be written.
   * @param data            The byte to write to the register on the device.
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public synchronized boolean write(int registerAddress, int data) {
    byte[] buffer = new byte[2];
    buffer[0] = (byte) registerAddress;
    buffer[1] = (byte) data;

    ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(2);
    dataToSendBuffer.put(buffer);

    return I2CJNI.i2CWrite(m_port, (byte) m_deviceAddress, dataToSendBuffer,
                           (byte) buffer.length) < 0;
  }

  /**
   * Execute a write transaction with the device.
   *
   *
Write multiple bytes to a register on a device and wait until the transaction is complete.
   *
   * @param data The data to write to the device.
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public synchronized boolean writeBulk(byte[] data) {
    ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(data.length);
    dataToSendBuffer.put(data);

    return I2CJNI.i2CWrite(m_port, (byte) m_deviceAddress, dataToSendBuffer,
                           (byte) data.length) < 0;
  }

  /**
   * Execute a write transaction with the device.
   *
   *
Write multiple bytes to a register on a device and wait until the transaction is complete.
   *
   * @param data The data to write to the device. Must be created using ByteBuffer.allocateDirect().
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public synchronized boolean writeBulk(ByteBuffer data, int size) {
    if (!data.isDirect()) {
      throw new IllegalArgumentException("must be a direct buffer");
    }
    if (data.capacity() < size) {
      throw new IllegalArgumentException(
          "buffer is too small, must be at least " + size);
    }

    return I2CJNI.i2CWrite(m_port, (byte) m_deviceAddress, data, (byte) size) < 0;
  }

  /**
   * Execute a read transaction with the device.
   *
   *
Read bytes from a device. Most I2C devices will auto-increment the register pointer
   * internally allowing you to read consecutive registers on a device in a single transaction.
   *
   * @param registerAddress The register to read first in the transaction.
   * @param count           The number of bytes to read in the transaction.
   * @param buffer          A pointer to the array of bytes to store the data read from the device.
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public boolean read(int registerAddress, int count, byte[] buffer) {
    requireNonNull(buffer, "Null return buffer was given");

    if (count < 1) {
      throw new BoundaryException("Value must be at least 1, " + count + " given");
    }

    byte[] registerAddressArray = new byte[1];
    registerAddressArray[0] = (byte) registerAddress;

    return transaction(registerAddressArray, registerAddressArray.length, buffer, count);
  }

  /**
   * Execute a read transaction with the device.
   *
   *
Read bytes from a device. Most I2C devices will auto-increment the register pointer
   * internally allowing you to read consecutive registers on a device in a single transaction.
   *
   * @param registerAddress The register to read first in the transaction.
   * @param count           The number of bytes to read in the transaction.
   * @param buffer          A buffer to store the data read from the device. Must be created using
   *                        ByteBuffer.allocateDirect().
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public boolean read(int registerAddress, int count, ByteBuffer buffer) {
    if (count < 1) {
      throw new BoundaryException("Value must be at least 1, " + count + " given");
    }

    if (!buffer.isDirect()) {
      throw new IllegalArgumentException("must be a direct buffer");
    }
    if (buffer.capacity() < count) {
      throw new IllegalArgumentException("buffer is too small, must be at least " + count);
    }

    ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(1);
    dataToSendBuffer.put(0, (byte) registerAddress);

    return transaction(dataToSendBuffer, 1, buffer, count);
  }

  /**
   * Execute a read only transaction with the device.
   *
   *
Read bytes from a device. This method does not write any data to prompt the device.
   *
   * @param buffer A pointer to the array of bytes to store the data read from the device.
   * @param count  The number of bytes to read in the transaction.
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public boolean readOnly(byte[] buffer, int count) {
    requireNonNull(buffer, "Null return buffer was given");
    if (count < 1) {
      throw new BoundaryException("Value must be at least 1, " + count + " given");
    }

    ByteBuffer dataReceivedBuffer = ByteBuffer.allocateDirect(count);

    int retVal = I2CJNI.i2CRead(m_port, (byte) m_deviceAddress, dataReceivedBuffer,
                                (byte) count);
    dataReceivedBuffer.get(buffer);
    return retVal < 0;
  }

  /**
   * Execute a read only transaction with the device.
   *
   *
Read bytes from a device. This method does not write any data to prompt the device.
   *
   * @param buffer A pointer to the array of bytes to store the data read from the device. Must be
   *               created using ByteBuffer.allocateDirect().
   * @param count  The number of bytes to read in the transaction.
   * @return Transfer Aborted... false for success, true for aborted.
   */
  public boolean readOnly(ByteBuffer buffer, int count) {
    if (count < 1) {
      throw new BoundaryException("Value must be at least 1, " + count
          + " given");
    }

    if (!buffer.isDirect()) {
      throw new IllegalArgumentException("must be a direct buffer");
    }
    if (buffer.capacity() < count) {
      throw new IllegalArgumentException("buffer is too small, must be at least " + count);
    }

    return I2CJNI.i2CRead(m_port, (byte) m_deviceAddress, buffer, (byte) count)
        < 0;
  }

  /*
   * Send a broadcast write to all devices on the I2C bus.
   *
   *
This is not currently implemented!
   *
   * @param registerAddress The register to write on all devices on the bus.
   * @param data            The value to write to the devices.
   */
  // public void broadcast(int registerAddress, int data) {
  // }

  /**
   * Verify that a device's registers contain expected values.
   *
   *
Most devices will have a set of registers that contain a known value that can be used to
   * identify them. This allows an I2C device driver to easily verify that the device contains the
   * expected value.
   *
   * @param registerAddress The base register to start reading from the device.
   * @param count           The size of the field to be verified.
   * @param expected        A buffer containing the values expected from the device.
   * @return true if the sensor was verified to be connected
   * @pre The device must support and be configured to use register auto-increment.
   */
  public boolean verifySensor(int registerAddress, int count,
                              byte[] expected) {
    // TODO: Make use of all 7 read bytes
    ByteBuffer dataToSendBuffer = ByteBuffer.allocateDirect(1);

    ByteBuffer deviceData = ByteBuffer.allocateDirect(4);
    for (int i = 0, curRegisterAddress = registerAddress;
         i < count; i += 4, curRegisterAddress += 4) {
      int toRead = count - i < 4 ? count - i : 4;
      // Read the chunk of data. Return false if the sensor does not
      // respond.
      dataToSendBuffer.put(0, (byte) curRegisterAddress);
      if (transaction(dataToSendBuffer, 1, deviceData, toRead)) {
        return false;
      }

      for (byte j = 0; j < toRead; j++) {
        if (deviceData.get(j) != expected[i + j]) {
          return false;
        }
      }
    }
    return true;
  }
}


text:
#ifndef SRC_SYSTEMS_LEVELRESTARTSYSTEM_H_
#define SRC_SYSTEMS_LEVELRESTARTSYSTEM_H_

#include <Box2D/Box2D.h>
#include <SFML/System.hpp>
#include <memory>
#include <anax/System.hpp>
#include <levels/TmxBox2dLevelLoader.h>

class LevelRestartSystem : public anax::System<LevelRestartSystem> {
public:
	LevelRestartSystem(TmxBox2dLevelLoader& levelLoader);
	~LevelRestartSystem();

	void update();

private:
	class LevelRestartSystemImpl;
	std::unique_ptr<LevelRestartSystemImpl> m_impl;

};

#endif /* SRC_SYSTEMS_LEVELRESTARTSYSTEM_H_ */


text:
#include "config.h"
#include "FloatPoint.h"

#include <Point.h>

namespace WebCore {

FloatPoint::FloatPoint(const BPoint& point)
    : m_x(point.x)
    , m_y(point.y)
{
}

FloatPoint::operator BPoint() const
{
    return BPoint(m_x, m_y);
}

} // namespace WebCore


text:
    pod 'DXLocationManager',:git=>"https://github.com/bindx/DXLocationManager.git"

##使用方法

######iOS 6 & 7

如果你是在 iOS6 & 7中使用,在Info.plist文件中添加NSLocationUsageDescription Boolean YES

######iOS 8 & 9

在info.plist表里面添加两条

NSLocationAlwaysUsageDescription Boolean YES

NSLocationWhenInUseUsageDescription Boolean YES

用于提示用户授权使用地理定位功能时的提示语。

####导入头文件 #import "DXLocationManager.h"

###Block

    [DXLocationManager getlocationWithBlock:^(double longitude, double latitude) {

     }];

###Delegate
    [GetLocationManger getMyLocationWithDelegate:YES];

    GetLocationManger.delegate = self;

####实现代理 --LocationManagerDelegate

    - (void)locationManager:(DXLocationManager *)manager   didGetLocation(CLLocationCoordinate2D)coordinate success:(BOOL)success{

    }


text:
#import "W2STCloudConfigViewController.h"
#include "W2STCloudConnectionViewController.h"

@interface W2STCloudConfigViewController ()

@end

@implementation W2STCloudConfigViewController

+(NSString*) getDeviceIdForNode:(BlueSTSDKNode*)node{
    NSString *temp = [node friendlyName];
    temp = [temp stringByReplacingOccurrencesOfString:@" " withString:@""];
    temp = [temp stringByReplacingOccurrencesOfString:@"@" withString:@"_"];
    return temp;
}

+(NSString*) getDeviceType:(BlueSTSDKNodeType)type{

    switch (type) {
        case BlueSTSDKNodeTypeNucleo:
            return @"NUCLEO";
        case BlueSTSDKNodeTypeSensor_Tile:
            return @"SENSOR_TILE";
        case BlueSTSDKNodeTypeBlue_Coin:
            return @"BLUE_COIN";
        case BlueSTSDKNodeTypeSTEVAL_WESU1:
            return @"STEVAL_WESU1";
        case BlueSTSDKNodeTypeGeneric:
        default:
            return @"GENERIC";
    }

}

/**
 * hide the keyboard when the user touch something outside the UITextField
 */
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    if (![[touch view] isKindOfClass:[UITextField class]]) {
        [self.view endEditing:YES];
    }
    [super touchesBegan:touches withEvent:event];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    if([segue.destinationViewController isKindOfClass:W2STCloudConnectionViewController.class]){
        W2STCloudConnectionViewController *temp = (W2STCloudConnectionViewController *)segue.destinationViewController;
        temp.node=self.node;
        temp.connectionFactoryBuilder=self;
    }

}

-(nullable id<W2STMQTTConnectionFactory>) buildConnectionFactory{
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                   reason:[NSString stringWithFormat:@"You must overwrite %@ in a subclass]",
                                           NSStringFromSelector(_cmd)]
                                 userInfo:nil];
    return nil;
}

@end


text:
package org.apache.omid.tso;

import java.util.concurrent.Future;

public interface LowWatermarkWriter {
    Future<Void> persistLowWatermark(final long lowWatermark);
}


text:
.class final Lcom/android/systemui/statusbar/stack/ViewState$1;
.super Lcom/android/systemui/statusbar/stack/AnimationProperties;
.source "ViewState.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/systemui/statusbar/stack/ViewState;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

# instance fields
.field mAnimationFilter:Lcom/android/systemui/statusbar/stack/AnimationFilter;

# direct methods
.method constructor <init>()V
    .locals 1

    invoke-direct {p0}, Lcom/android/systemui/statusbar/stack/AnimationProperties;-><init>()V

    new-instance v0, Lcom/android/systemui/statusbar/stack/AnimationFilter;

    invoke-direct {v0}, Lcom/android/systemui/statusbar/stack/AnimationFilter;-><init>()V

    iput-object v0, p0, Lcom/android/systemui/statusbar/stack/ViewState$1;->mAnimationFilter:Lcom/android/systemui/statusbar/stack/AnimationFilter;

    return-void
.end method

# virtual methods
.method public getAnimationFilter()Lcom/android/systemui/statusbar/stack/AnimationFilter;
    .locals 1

    iget-object v0, p0, Lcom/android/systemui/statusbar/stack/ViewState$1;->mAnimationFilter:Lcom/android/systemui/statusbar/stack/AnimationFilter;

    return-object v0
.end method


text:
#ifndef GAME_H
#define GAME_H

#include <QList>
#include "PlayerProfile.h"

class DebugMetricsMonitor;
class LevelProgression;
class LevelProgressionList;
class QObject;
class UiInternal;

/**
 * @brief The top-level Game object for VoltAir.
 *
 * This singleton class is effectively the mainline of the game as well as the parent object for all
 * game-related objects (e.g. PlayerProfile, LevelProgression).
 */
class Game : public QObject {
    Q_OBJECT
public:
    virtual ~Game();

    /**
     * @brief Initialize the game.
     *
     * This includes instantiating the UI, reading in the level progressions, player profiles
     * and making signal/slot connections to the various submodules.
     *
     */
    void init();
    /**
     * @brief Returns if any of the UI screens are active.
     */
    bool isUiActive() const { return mIsUiActive; }
    /**
     * @brief Returns the unique LevelProgressionList for the game.
     */
    LevelProgressionList* getLevelProgressionList() const { return mLevelProgressionList; }
    /**
     * @brief Informs the engine to load the current level.
     *
     * The call to the engine is only made if the PlayerProfile is loaded and it has
     * a LevelProgression from which it can get the current level to load.
     */
    void tryLoadLevel();
    /**
     * @brief Returns the unique DebugMetricsMonitor for the game.
     */
    DebugMetricsMonitor* getDebugMetricsMonitor() const { return mDebugMetricsMonitor; }
    /**
     * @brief Updates score and completes level if appropriate.
     * @param playerId Unique ID <tt>[0, 3]</tt> of the player
     * @param amountChanged Delta of the score change
     */
    void updatePlayerScore(int playerId, int amountChanged);

    /**
     * @brief Returns the main UI element.
     */
    Q_INVOKABLE UiInternal* getUi() const { return mUi; }
    /**
     * @brief Returns the current LevelProgression selected by the player.
     * @note The returned value can be non-@c null even if Engine::getLevel() is @c null.
     */
    Q_INVOKABLE LevelProgression* getCurrentLevelProgression() const {
        return mCurrentLevelProgression;
    }
    /**
     * @brief Returns the current LevelInfo selected by the player.
     * @note The returned value is always non-@c null if getCurrentLevelProgression is non-@c null.
     * That is, selections of LevelInfo can be implicit based on the previous level played in a
     * LevelProgression.
     */
    Q_INVOKABLE LevelInfo* getCurrentLevelInfo() const;
    /**
     * @brief Returns whether or not the specified environment is unlocked in the specified
     * progression.
     * @param progressionName Name of LevelProgression in which @p environmentName resides
     * @param environmentName Name of Environment whose lock status to check
     */
    Q_INVOKABLE bool isEnvironmentUnlocked(const QString& progressionName,
            const QString& environmentName) const;
    /**
     * @brief Returns whether or not the specified level is unlocked in the specified progression.
     * @param progressionName Name of LevelProgression in which @p levelName resides
     * @param levelName Name of LevelInfo whose lock status to check
     */
    Q_INVOKABLE bool isLevelUnlocked(const QString& progressionName,
            const QString& levelName) const;
    /**
     * @brief Returns the highest number of stars achieved on a level, as logged in the
     * PlayerProfile.
     * @note If @p progressionName is a multiplayer LevelProgression, this function will always
     * return a invalid (i.e. negative) star score.
     * @param progressionName Name of single player LevelProgression in which @p levelName resides
     * @param levelName Name of the LevelInfo whose number of stars is being queried
     */
    Q_INVOKABLE int getNumStars(const QString& progressionName, const QString& levelName) const;
    /**
     * @brief Returns the index of the environment last played in the specified progression.
     * @param progressionName Name of LevelProgression to query
     */
    Q_INVOKABLE int getLastPlayedEnvironmentIndex(const QString& progressionName) const;
    /**
     * @brief Returns the index of the last played level in a given environment.
     * @param progressionName Name of LevelProgression in which @p environmentName resides
     * @param environmentName Name of Environment to query
     */
    Q_INVOKABLE int getLastPlayedLevelIndexInEnvironment(const QString& progressionName,
            const QString& environmentName) const;
    /**
     * @brief Unlocks a Google Play Games Services achievement.
     * @note This function only has an effect on an Android device.
     * @param name Android resource name used to locate the achievement id
     * @param immediately Whether or not to sync the achievement change with Google Play Games
     * Services now
     */
    Q_INVOKABLE void unlockAchievement(const QString& name, bool immediately = true);
    /**
     * @brief Increments a Google Play Games Services incremental achievement.
     * @note This function only has an effect on an Android device.
     * @param name Android resource name used to locate the achievement id
     * @param numSteps Number of steps to increment the achievement
     * @param immediately Whether or not to sync the achievement change with Google Play Games
     * Services now
     */
    Q_INVOKABLE void incrementAchievement(const QString& name, int numSteps,
            bool immediately = false);
    /**
     * @brief Sets a Google Play Games Services incremental achievement to have a minimum number of
     * steps.
     * @note This function only has an effect on an Android device.
     * @param name Android resource name used to locate the achievement id
     * @param minSteps Lower bound for incremental progress
     * @param immediately Whether or not to sync the achievement change with Google Play Games
     * Services now
     */
    Q_INVOKABLE void setAchievementSteps(const QString& name, int minSteps,
            bool immediately = false);
    /**
     * @brief Reveals a Google Play Games Services achievement.
     * @note This function only has an effect on an Android device.
     * @param name Android resource name used to locate the achievement id
     * @param immediately Whether or not to sync the achievement change with Google Play Games
     * Services now
     */
    Q_INVOKABLE void revealAchievement(const QString& name, bool immediately = true);

    /**
     * @brief Gets the singleton Game.
     */
    static Game* getInstance();
signals:

    /**
     * @brief Emitted on level completed.
     *
     * This is emitted upon completion of the call to onLevelCompleted().
     *
     * @param gameIsOver Whether this level completion resulted in the game being over
     * @param oneStarThreshold Threshold for a single star on the completed level
     * @param twoStarThreshold Threshold for a two stars on the completed level
     * @param threeStarThreshold Threshold for a three stars on the completed level
     * @param fourStarThreshold Threshold for a four stars on the completed level
     * @param playerScore Player's score on the completed level
     */
    void levelCompleted(bool gameIsOver, int oneStarThreshold, int twoStarThreshold,
            int threeStarThreshold, int fourStarThreshold, int playerScore);

    /**
     * @brief Emitted when a player's score changes.
     * @param playerId Unique ID of the player (0-3)
     * @param score Player's new score
     */
    void playerScoreChanged(int playerId, int score);

public slots:
    /**
     * @brief Respond to a level being completed.
     */
    void onLevelCompleted();

    /**
     * @brief Respond to a change to the state of GPGS cloud sign-in.
     * @param signedIntoCloud @c true if notifying of sign-in success
     */
    void onSignedIntoCloudChanged(bool signedIntoCloud);

    /**
     * @brief Respond to the GPGS cloud data being loaded.
     * @param statusCode Status of load, zero implying success, non-zero is error
     * @param data String encoded loaded save game data or a null string if loading error occurred
     */
    void onCloudDataLoaded(int statusCode, const QString& data);

    /**
     * @brief Respond to a conflict in the loading of GPGS cloud data.
     * @param localData String encoded local save game data that is in conflict
     * @param serverData String encoded cloud save game data that is in conflict
     * @returns JSON representing the conflicting GPGS cloud data, when possible
     */
    QString onCloudDataConflict(const QString& localData, const QString& serverData);

private slots:
    void onUiActiveChanged(bool isActive);
    void onChangeLevelProgressionRequested();
    void onChangeLevelRequested();
    void onOpeningCinematicCompleted();
    void onPlayLevelRequested(LevelProgression* levelProgression, const QString& levelName);
    void onPlayNextLevelRequested();
    void onQuitRequested();
    void onSignIntoCloudRequested();
    void onMuteBGMRequested();
    void onUnmuteBGMRequested();
    void onBeforeUpdate();
    void onAfterUpdate();
    void onLevelChanged();

private:
    struct ScoringInfo {
        int oneStarThreshold;
        int twoStarThreshold;
        int threeStarThreshold;
        int perfectScore;
    };

    Game(QObject* parent = nullptr);

    ScoringInfo getScoringInfo() const;
    int getStarScore(int playerScore) const;
    QString getLevelTrackerTag(const QString& eventName) const;
    void abandonCurrentLevel();

    DebugMetricsMonitor* mDebugMetricsMonitor = nullptr;
    bool mIsInitialized = false;
    bool mIsUiActive = false;
    volatile bool mIsPlayingLevel = false;
    LevelProgressionList* mLevelProgressionList = nullptr;
    LevelProgression* mCurrentLevelProgression = nullptr;
    PlayerProfile mPlayerProfile;
    UiInternal* mUi = nullptr;
    // Trigger Energy Crisis achievement by collecting mScoreUpdateComboAchievement points in under
    // mTimeForComboAchievement seconds.
    int mScoreUpdateComboAchievement = 10;
    float mTimeForComboAchievement = 5.0f;
    // Event queue counter for the number of score updates that have occured over the last
    // mTimeForComboAchievement seconds.
    QList<long long> mScoreUpdateTimes;

    static Game* sInstance;

    // A [0,1) value that describes where between completionThreshold and activationThreshold a two
    // star score is awarded.  A value of 0 grants two stars at exactly the completionThreshold and
    // above. A value of 0.5 would grant two stars for a score greater than or equal to the average
    // of completionThreshold and activationThreshold.
    static constexpr float TWO_STAR_THRESHOLD_FACTOR = 0.35f;
    // A [0,1) value that describes where between completionThreshold and the calculated
    // twoStarThreshold a three star score is awarded. A value of 0.5 would grant three stars for
    // a score greater than or equal to the average of completionThreshold and the calculated
    // twoStarThreshold.
    static constexpr float THREE_STAR_THRESHOLD_FACTOR = 0.5f;
};
Q_DECLARE_METATYPE(Game*)
#endif


text:
template <typename Dtype>
__global__ void im2col_kernel(const int n, const Dtype* data_im,
                              const int height, const int width,
                              const int ksize_h, const int ksize_w,
                              const int pad_h, const int pad_w,
                              const int stride_h, const int stride_w,
                              const int dilation_h, const int dilation_w,
                              const int height_col, const int width_col,
    Dtype* data_col) {
  CUDA_KERNEL_LOOP(index, n) {
    int w_out = index % width_col;
    index /= width_col;
    int h_out = index % height_col;
    int channel_in = index / height_col;
    int channel_out = channel_in * ksize_h * ksize_w;
    int h_in = h_out * stride_h - pad_h;
    int w_in = w_out * stride_w - pad_w;
    data_col += (channel_out * height_col + h_out) * width_col + w_out;
    data_im += (channel_in * height + h_in) * width + w_in;
    for (int i = 0; i < ksize_h; ++i) {
      for (int j = 0; j < ksize_w; ++j) {
        int h = h_in + i * dilation_h;
        int w = w_in + j * dilation_w;
        *data_col = (h >= 0 && w >= 0 && h < height && w < width) ?
          data_im[i * dilation_h * width + j * dilation_w] : ScalarConvert<int, Dtype>::to(0);
        data_col += height_col * width_col;
      }
    }
  }
}

template <typename Dtype>
void im2col(cudaStream_t stream, const Dtype* data_im, const int channels,
            const int height, const int width,
            const int ksize_h, const int ksize_w, const int pad_h,
            const int pad_w, const int stride_h, const int stride_w,
            const int dilation_h, const int dilation_w, Dtype* data_col) {
  // We are going to launch channels * height_col * width_col kernels, each
  // kernel responsible for copying a single-channel grid.
  int height_col = (height + 2 * pad_h - (dilation_h * (ksize_h - 1) + 1))
                   / stride_h + 1;
  int width_col = (width + 2 * pad_w - (dilation_w * (ksize_w - 1) + 1))
                  / stride_w + 1;
  int num_kernels = channels * height_col * width_col;
  // Launch
  im2col_kernel <<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS, 0, stream>>> (
      num_kernels, data_im, height, width, ksize_h, ksize_w,
      pad_h, pad_w, stride_h, stride_w,
      dilation_h, dilation_w,
      height_col, width_col, data_col
  );
  THCudaCheck(cudaGetLastError());
}

template <typename Dtype, typename Acctype>
__global__ void col2im_kernel(const int n, const Dtype* data_col,
                                  const int height, const int width, const int channels,
                                  const int kernel_h, const int kernel_w,
                                  const int pad_h, const int pad_w,
                                  const int stride_h, const int stride_w,
                                  const int dilation_h, const int dilation_w,
                                  const int height_col, const int width_col,
                                  Dtype* data_im) {
  CUDA_KERNEL_LOOP(index, n) {
    Acctype val = Acctype(0);
    const int w_im = index % width + pad_w;
    const int h_im = (index / width) % height + pad_h;
    const int c_im = index / (width * height);
    int kernel_extent_w = (kernel_w - 1) * dilation_w + 1;
    int kernel_extent_h = (kernel_h - 1) * dilation_h + 1;
    // compute the start and end of the output
    const int w_col_start =
      (w_im < kernel_extent_w) ? 0 : (w_im - kernel_extent_w) / stride_w + 1;
    const int w_col_end = min(w_im / stride_w + 1, width_col);
    const int h_col_start =
      (h_im < kernel_extent_h) ? 0 : (h_im - kernel_extent_h) / stride_h + 1;
    const int h_col_end = min(h_im / stride_h + 1, height_col);
    // TODO: use LCM of stride and dilation to avoid unnecessary loops
    for (int h_col = h_col_start; h_col < h_col_end; h_col += 1) {
      for (int w_col = w_col_start; w_col < w_col_end; w_col += 1) {
        int h_k = (h_im - h_col * stride_h);
        int w_k = (w_im - w_col * stride_w);
        if (h_k % dilation_h == 0 && w_k % dilation_w == 0) {
          h_k /= dilation_h;
          w_k /= dilation_w;
          int data_col_index = (((c_im * kernel_h + h_k) * kernel_w + w_k) *
                                height_col + h_col) * width_col + w_col;
          val += data_col[data_col_index];
        }
      }
    }
    data_im[index] = ScalarConvert<Acctype, Dtype>::to(val);
  }
}

template <typename Dtype, typename Acctype>
void col2im(cudaStream_t stream, const Dtype* data_col, const int channels,
            const int height, const int width,
            const int patch_h, const int patch_w, const int pad_h,
            const int pad_w, const int stride_h, const int stride_w,
            const int dilation_h, const int dilation_w, Dtype* data_im) {
  int height_col = (height + 2 * pad_h - (dilation_h * (patch_h - 1) + 1))
                   / stride_h + 1;
  int width_col = (width + 2 * pad_w - (dilation_w * (patch_w - 1) + 1))
                   / stride_w + 1;
  int num_kernels = channels * height * width;
  // To avoid involving atomic operations, we will launch one kernel per
  // bottom dimension, and then in the kernel add up the top dimensions.
  col2im_kernel<Dtype, Acctype> <<<GET_BLOCKS(num_kernels), CUDA_NUM_THREADS, 0, stream>>> (
      num_kernels, data_col, height, width, channels,
      patch_h, patch_w, pad_h, pad_w, stride_h, stride_w,
      dilation_h, dilation_w,
      height_col, width_col, data_im
  );
  THCudaCheck(cudaGetLastError());
}

#endif


text:
import logging

from loqusdb.build_models.variant import get_variant_id

from loqusdb.models import ProfileVariant

LOG = logging.getLogger(__name__)

def get_maf(variant):
    """
    Gets the MAF (minor allele frequency) tag from the info field for the
    variant.

    Args:
        variant (cyvcf2.Variant)

    Returns:
        maf (float): Minor allele frequency

    """

    return variant.INFO.get("MAF")

def build_profile_variant(variant):
    """Returns a ProfileVariant object

    Args:
        variant (cyvcf2.Variant)

    Returns:
        variant (models.ProfileVariant)
    """

    chrom = variant.CHROM
    if chrom.startswith(("chr", "CHR", "Chr")):
        chrom = chrom[3:]

    pos = int(variant.POS)

    variant_id = get_variant_id(variant)

    ref = variant.REF
    alt = variant.ALT[0]

    maf = get_maf(variant)

    profile_variant = ProfileVariant(
        variant_id=variant_id, chrom=chrom, pos=pos, ref=ref, alt=alt, maf=maf, id_column=variant.ID
    )

    return profile_variant


text:
'use strict';

//Setting up route
angular.module('metrics').config(['$stateProvider',
	function($stateProvider) {
		// Metrics state routing
		$stateProvider.
		state('listMetrics', {
			url: '/metrics',
			templateUrl: 'modules/metrics/views/list-metrics.client.view.html'
		}).
		state('createMetric', {
			url: '/metrics/create',
			templateUrl: 'modules/metrics/views/create-metric.client.view.html'
		}).
		state('viewMetric', {
			url: '/metrics/:metricId',
			templateUrl: 'modules/metrics/views/view-metric.client.view.html'
		}).
		state('editMetric', {
			url: '/metrics/:metricId/edit',
			templateUrl: 'modules/metrics/views/edit-metric.client.view.html'
		});
	}
]);


text:
Resistance.GamesShowRoute = Ember.Route.extend({
  model: function (params) {
    return this.store.find('game', params.id);
  }
});


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Boston J. Nat. Hist. 6:182. 1850

#### Original name
null

### Remarks
null


text:
require 'thor'

module Desky
  require 'desky/project_manager'
  require 'desky/errors'
  require 'desky/version'
  require 'psych'

  # whoop whoop
  class Desky < Thor
    include Thor::Actions

    PROJECT_MANAGER = ProjectManager.new

    def self.configure
      yield PROJECT_MANAGER.config if block_given?
    end

    map "-o" => :open
    map "-d" => :delete
    map "-e" => :edit
    map "-n" => :new
    map "-c" => :new
    map "-l" => :list
    map "-s" => :show
    map "-v" => :version

    desc '(open) PROJECT (-o)', 'Opens your project!'
    def open(name)
      PROJECT_MANAGER.run_project name
    end

    desc 'list', "Lists all your projects."
    def list
      say_status "Projects: ", PROJECT_MANAGER.all*"  ", :blue
    end

    desc 'show PROJECT (-s)', 'Show a project and its tasks.'
    def show(name)
      PROJECT_MANAGER.read name
    end

    desc 'new PROJECT (-n|-c)', 'Make a new project.'
    def new(name)
      PROJECT_MANAGER.create name
    end

    desc 'edit PROJECT (-e)', 'Edit your project. '
    def edit(name)
      PROJECT_MANAGER.update name
    end

    desc 'delete PROJECT (-d)', 'Delete a project. '
    def delete(name)
      PROJECT_MANAGER.delete name if yes? "Are you sure?"
    end

    desc 'version (-v)', 'Shows Desky version'
    def version
      say VERSION
    end

    def method_missing(name)
      return send :open, name if PROJECT_MANAGER.all.include? name.to_s
      say "Could not find task or project \"#{name}\"!", :red
      send :help
    end
  end
end


text:
package org.opencompare.analysis.analyzer

/**
  * Created by gbecan on 11/12/15.
  */
object StatsAnalyzer {

}


text:
from marshmallow import Schema, fields, ValidationError
from contracts_api.api.models import Stage, Flow

def validate_not_none(stage_property):
    '''
    Validates if this is not none
    '''
    if stage_property is not None and stage_property != '':
        return True

    raise ValidationError('Stage Property cannot be None or empty')

class StagePropertySchema(Schema):
    '''
    Serialize the properties of an individual stage
    '''
    stage_property = fields.String(required=True, validate=validate_not_none)

    class Meta:
        fields = ('id', 'stage_property')

class StageSchema(Schema):
    '''
    Seralize an individual stage
    '''
    name = fields.String(validate=validate_not_none)
    stage_properties = fields.Nested(StagePropertySchema(exclude=('id', )), many=True)

    class Meta:
        fields = ('id', 'name', 'stage_properties')

def validate_is_stage(input_stage):
    stage = Stage.select().where(Stage.id==int(input_stage.get('id'))).first()

    if stage:
        return True

    raise ValidationError('Not a valid stage')

def validate_is_flow(flow_name):
    flow = Flow.select().where(Flow.flow_name==flow_name).first()

    if flow:
        return True

    raise ValidationError('Not a valid flow name')

def validate_stage_order(input_order):
    # << is a peewee operator for SQL IN
    if len(input_order) == 0:
        raise ValidationError('You must specify at least one stage')

    stages = Stage.select(Stage.id).where(Stage.id << input_order)

    if stages.count() != len(input_order):
        stage_ids = [i.id for i in stages]
        bad_stage_ids = list(set(stage_ids).symmetric_difference(set(input_order)))
        raise ValidationError('The following stage ids do not exist: {stages}'.format(
            stages=', '.join([unicode(i) for i in bad_stage_ids])
        ))

    return True

class FlowSchema(Schema):
    '''
    Serialize an individual flow
    '''
    flow_name = fields.String(required=True)
    stage_order = fields.List(fields.Integer, required=True, validate=validate_stage_order)

    class Meta:
        fields = ('id', 'flow_name', 'stage_order')

class ContractSchema(Schema):
    '''
    Serialize an individual contract
    '''
    current_stage = fields.Nested(StageSchema(exclude=('stage_properties',)), validate=validate_is_stage)
    flow = fields.Nested(FlowSchema(), validate=validate_is_flow, attribute='flow_name')

    class Meta:
        fields = (
            'id', 'item_number', 'spec_number', 'department',
            'commodity_title', 'status_comments', 'current_stage',
            'flow'
        )


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>core</artifactId>
        <groupId>com.awplab.core</groupId>
        <version>1.0.2-SNAPSHOT</version>
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <artifactId>scheduler</artifactId>

    <packaging>pom</packaging>

    <name>AWPLab Core - Scheduler</name>

    <modules>
        <module>service</module>
        <module>command</module>
        <module>admin</module>
    </modules>

</project>


text:
package com.google.auth.oauth2;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import com.google.api.client.http.HttpTransport;
import com.google.auth.TestUtils;
import com.google.auth.http.HttpTransportFactory;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link DownscopedCredentials}. */
@RunWith(JUnit4.class)
public class DownscopedCredentialsTest {

  private static final String SA_PRIVATE_KEY_PKCS8 =
      "-----BEGIN PRIVATE KEY-----\n"
          + "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALX0PQoe1igW12i"
          + "kv1bN/r9lN749y2ijmbc/mFHPyS3hNTyOCjDvBbXYbDhQJzWVUikh4mvGBA07qTj79Xc3yBDfKP2IeyYQIFe0t0"
          + "zkd7R9Zdn98Y2rIQC47aAbDfubtkU1U72t4zL11kHvoa0/RuFZjncvlr42X7be7lYh4p3NAgMBAAECgYASk5wDw"
          + "4Az2ZkmeuN6Fk/y9H+Lcb2pskJIXjrL533vrDWGOC48LrsThMQPv8cxBky8HFSEklPpkfTF95tpD43iVwJRB/Gr"
          + "CtGTw65IfJ4/tI09h6zGc4yqvIo1cHX/LQ+SxKLGyir/dQM925rGt/VojxY5ryJR7GLbCzxPnJm/oQJBANwOCO6"
          + "D2hy1LQYJhXh7O+RLtA/tSnT1xyMQsGT+uUCMiKS2bSKx2wxo9k7h3OegNJIu1q6nZ6AbxDK8H3+d0dUCQQDTrP"
          + "SXagBxzp8PecbaCHjzNRSQE2in81qYnrAFNB4o3DpHyMMY6s5ALLeHKscEWnqP8Ur6X4PvzZecCWU9BKAZAkAut"
          + "LPknAuxSCsUOvUfS1i87ex77Ot+w6POp34pEX+UWb+u5iFn2cQacDTHLV1LtE80L8jVLSbrbrlH43H0DjU5AkEA"
          + "gidhycxS86dxpEljnOMCw8CKoUBd5I880IUahEiUltk7OLJYS/Ts1wbn3kPOVX3wyJs8WBDtBkFrDHW2ezth2QJ"
          + "ADj3e1YhMVdjJW5jqwlD/VNddGjgzyunmiZg0uOXsHXbytYmsA545S8KRQFaJKFXYYFo2kOjqOiC1T2cAzMDjCQ"
          + "==\n-----END PRIVATE KEY-----\n";

  private static final CredentialAccessBoundary CREDENTIAL_ACCESS_BOUNDARY =
      CredentialAccessBoundary.newBuilder()
          .addRule(
              CredentialAccessBoundary.AccessBoundaryRule.newBuilder()
                  .setAvailableResource("//storage.googleapis.com/projects/_/buckets/bucket")
                  .addAvailablePermission("inRole:roles/storage.objectViewer")
                  .build())
          .build();

  static class MockStsTransportFactory implements HttpTransportFactory {

    MockStsTransport transport = new MockStsTransport();

    @Override
    public HttpTransport create() {
      return transport;
    }
  }

  @Test
  public void refreshAccessToken() throws IOException {
    MockStsTransportFactory transportFactory = new MockStsTransportFactory();

    GoogleCredentials sourceCredentials =
        getServiceAccountSourceCredentials(/* canRefresh= */ true);

    DownscopedCredentials downscopedCredentials =
        DownscopedCredentials.newBuilder()
            .setSourceCredential(sourceCredentials)
            .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY)
            .setHttpTransportFactory(transportFactory)
            .build();

    AccessToken accessToken = downscopedCredentials.refreshAccessToken();

    assertEquals(transportFactory.transport.getAccessToken(), accessToken.getTokenValue());

    // Validate CAB specific params.
    Map<String, String> query =
        TestUtils.parseQuery(transportFactory.transport.getRequest().getContentAsString());
    assertNotNull(query.get("options"));
    assertEquals(CREDENTIAL_ACCESS_BOUNDARY.toJson(), query.get("options"));
    assertEquals(
        "urn:ietf:params:oauth:token-type:access_token", query.get("requested_token_type"));
  }

  @Test
  public void refreshAccessToken_userCredentials_expectExpiresInCopied() throws IOException {
    // STS only returns expires_in if the source access token belongs to a service account.
    // For other source credential types, we can copy the source credentials expiration as
    // the generated downscoped token will always have the same expiration time as the source
    // credentials.

    MockStsTransportFactory transportFactory = new MockStsTransportFactory();
    transportFactory.transport.setReturnExpiresIn(false);

    GoogleCredentials sourceCredentials = getUserSourceCredentials();

    DownscopedCredentials downscopedCredentials =
        DownscopedCredentials.newBuilder()
            .setSourceCredential(sourceCredentials)
            .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY)
            .setHttpTransportFactory(transportFactory)
            .build();

    AccessToken accessToken = downscopedCredentials.refreshAccessToken();

    assertEquals(transportFactory.transport.getAccessToken(), accessToken.getTokenValue());

    // Validate that the expires_in has been copied from the source credential.
    assertEquals(
        sourceCredentials.getAccessToken().getExpirationTime(), accessToken.getExpirationTime());
  }

  @Test
  public void refreshAccessToken_cantRefreshSourceCredentials_throws() throws IOException {
    MockStsTransportFactory transportFactory = new MockStsTransportFactory();

    GoogleCredentials sourceCredentials =
        getServiceAccountSourceCredentials(/* canRefresh= */ false);

    DownscopedCredentials downscopedCredentials =
        DownscopedCredentials.newBuilder()
            .setSourceCredential(sourceCredentials)
            .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY)
            .setHttpTransportFactory(transportFactory)
            .build();

    try {
      downscopedCredentials.refreshAccessToken();
      fail("Should fail as the source credential should not be able to be refreshed.");
    } catch (IOException e) {
      assertEquals("Unable to refresh the provided source credential.", e.getMessage());
    }
  }

  @Test
  public void builder_noSourceCredential_throws() {
    try {
      DownscopedCredentials.newBuilder()
          .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY)
          .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY)
          .build();
      fail("Should fail as the source credential is null.");
    } catch (NullPointerException e) {
      // Expected.
    }
  }

  @Test
  public void builder_noCredentialAccessBoundary_throws() throws IOException {
    try {
      DownscopedCredentials.newBuilder()
          .setHttpTransportFactory(OAuth2Utils.HTTP_TRANSPORT_FACTORY)
          .setSourceCredential(getServiceAccountSourceCredentials(/* canRefresh= */ true))
          .build();
      fail("Should fail as no access boundary was provided.");
    } catch (NullPointerException e) {
      // Expected.
    }
  }

  @Test
  public void builder_noTransport_defaults() throws IOException {
    GoogleCredentials sourceCredentials =
        getServiceAccountSourceCredentials(/* canRefresh= */ true);
    DownscopedCredentials credentials =
        DownscopedCredentials.newBuilder()
            .setSourceCredential(sourceCredentials)
            .setCredentialAccessBoundary(CREDENTIAL_ACCESS_BOUNDARY)
            .build();

    GoogleCredentials scopedSourceCredentials =
        sourceCredentials.createScoped("https://www.googleapis.com/auth/cloud-platform");
    assertEquals(scopedSourceCredentials, credentials.getSourceCredentials());
    assertEquals(CREDENTIAL_ACCESS_BOUNDARY, credentials.getCredentialAccessBoundary());
    assertEquals(OAuth2Utils.HTTP_TRANSPORT_FACTORY, credentials.getTransportFactory());
  }

  private static GoogleCredentials getServiceAccountSourceCredentials(boolean canRefresh)
      throws IOException {
    GoogleCredentialsTest.MockTokenServerTransportFactory transportFactory =
        new GoogleCredentialsTest.MockTokenServerTransportFactory();

    String email = "service-account@google.com";

    ServiceAccountCredentials sourceCredentials =
        ServiceAccountCredentials.newBuilder()
            .setClientEmail(email)
            .setPrivateKey(ServiceAccountCredentials.privateKeyFromPkcs8(SA_PRIVATE_KEY_PKCS8))
            .setPrivateKeyId("privateKeyId")
            .setProjectId("projectId")
            .setHttpTransportFactory(transportFactory)
            .build();

    transportFactory.transport.addServiceAccount(email, "accessToken");

    if (!canRefresh) {
      transportFactory.transport.setError(new IOException());
    }

    return sourceCredentials.createScoped("https://www.googleapis.com/auth/cloud-platform");
  }

  private static GoogleCredentials getUserSourceCredentials() {
    GoogleCredentialsTest.MockTokenServerTransportFactory transportFactory =
        new GoogleCredentialsTest.MockTokenServerTransportFactory();
    transportFactory.transport.addClient("clientId", "clientSecret");
    transportFactory.transport.addRefreshToken("refreshToken", "accessToken");
    AccessToken accessToken = new AccessToken("accessToken", new Date());
    return UserCredentials.newBuilder()
        .setClientId("clientId")
        .setClientSecret("clientSecret")
        .setRefreshToken("refreshToken")
        .setAccessToken(accessToken)
        .setHttpTransportFactory(transportFactory)
        .build();
  }
}


text:
'use strict';

describe('concat iterator', function () {

	var ConcatIterator = require('../../src/iterators/concat');
	var ArrayIterator = require('../../src/iterators/array');
	var expect = require('chai').expect;

	it('result is undefined before moving to first element', function () {

		var concat = new ConcatIterator([]);
		expect(concat.getCurrent()).to.be.undefined;
	});

	it('completes straight way when there are no child iterators', function () {

		var concat = new ConcatIterator([]);
		expect(concat.moveNext()).to.eql(false);
	});

	it('completes immediately if child iterators are empty', function () {

		var mockIterator1 = {
			moveNext: function () {
				return false;
			},

			getCurrent: function () {
				return null;
			},
		};

		var mockIterator2 = {
			moveNext: function () {
				return false;
			},

			getCurrent: function () {
				return null;
			},
		};

		var concat = new ConcatIterator([mockIterator1, mockIterator2]);
		expect(concat.moveNext()).to.eql(false);
	});

	it('completes when all child iterators complete', function () {

		var concat = new ConcatIterator([new ArrayIterator([1, 2]), new ArrayIterator([3, 4])]);
		expect(concat.moveNext()).to.eql(true);
		expect(concat.getCurrent()).to.eql(1);

		expect(concat.moveNext()).to.eql(true);
		expect(concat.getCurrent()).to.eql(2);

		expect(concat.moveNext()).to.eql(true);
		expect(concat.getCurrent()).to.eql(3);

		expect(concat.moveNext()).to.eql(true);
		expect(concat.getCurrent()).to.eql(4);

		expect(concat.moveNext()).to.eql(false);
	});

	it('can always get last item at the end', function () {

		var testObject = new ConcatIterator([new ArrayIterator([1, 2]), new ArrayIterator([3, 4])]);

		testObject.moveNext();
		testObject.moveNext();
		testObject.moveNext();
		testObject.moveNext();
		testObject.moveNext();

		expect(testObject.getCurrent()).to.eql(4);
	});

});


text:
<?php
namespace AppBundle\Form\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class TypePossible extends Constraint
{
    public $message = 'Nous sommes désolés, les billets à la journée ne sont plus disponibles pour aujourd\'hui.';

	public function getTargets()
	{
		return self::CLASS_CONSTRAINT;
	}
}