text:
import { WriteOnlyConstants } from "@glimmer/program";

export default class DebugConstants extends WriteOnlyConstants {
  getFloat(value: number): number {
    return this.floats[value];
  }

  getNegative(value: number): number {
    return this.negatives[value];
  }

  getString(value: number): string {
    return this.strings[value];
  }

  getStringArray(value: number): string[] {
    let names = this.getArray(value);
    let _names: string[] = new Array(names.length);

    for (let i = 0; i < names.length; i++) {
      let n = names[i];
      _names[i] = this.getString(n);
    }

    return _names;
  }

  getArray(value: number): number[] {
    return (this.arrays as number[][])[value];
  }

  resolveHandle<T>(s: number): T {
    return { handle: s } as any as T;
  }

  getSerializable<T>(s: number): T {
    return JSON.parse(this.strings[s]) as T;
  }
}


text:
@interface AEBlockChannel ()
@property (nonatomic, copy) AEBlockChannelBlock block;
@end

@implementation AEBlockChannel
@synthesize block = _block;

- (id)initWithBlock:(AEBlockChannelBlock)block {
    if ( !(self = [super init]) ) self = nil;
    self.volume = 1.0;
    self.pan = 0.0;
    self.block = block;
    self.channelIsMuted = NO;
    self.channelIsPlaying = YES;
    return self;
}

+ (AEBlockChannel*)channelWithBlock:(AEBlockChannelBlock)block {
    return [[[AEBlockChannel alloc] initWithBlock:block] autorelease];
}

-(void)dealloc {
    self.block = nil;
    [super dealloc];
}

static OSStatus renderCallback(id                        channel,
                               AEAudioController        *audioController,
                               const AudioTimeStamp     *time,
                               UInt32                    frames,
                               AudioBufferList          *audio) {
    AEBlockChannel *THIS = (AEBlockChannel*)channel;
    THIS->_block(time, frames, audio);
    return noErr;
}

-(AEAudioControllerRenderCallback)renderCallback {
    return renderCallback;
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Cartalyst\Sentinel\Tests;

use Cartalyst\Sentinel\Permissions\PermissionsTrait;
use Cartalyst\Sentinel\Permissions\PermissionsInterface;
use Mockery as m;
use PHPUnit_Framework_TestCase;

class PermissionsTraitTest extends PHPUnit_Framework_TestCase
{
    /**
     * Close mockery.
     *
     * @return void
     */
    public function tearDown()
    {
        m::close();
    }

    public function testPermissionsClassSetterAndGetter()
    {
        $secondaryPermissions = [
            [
                'test1' => true,
            ],
            [
                'test1' => false,
            ]
        ];

        $permissions = new PermissionsStub([
            'test' => true,
            'test2' => false,
        ], $secondaryPermissions);

        $secondaryPermissions[] = [
            'test2' => true,
        ];

        $permissions->setSecondaryPermissions($secondaryPermissions);

        $this->assertTrue($permissions->hasAccess('test'));
        $this->assertFalse($permissions->hasAccess('test', 'test1'));
        $this->assertFalse($permissions->hasAccess(['test', 'test1']));

        $this->assertTrue($permissions->hasAnyAccess('test'));
        $this->assertTrue($permissions->hasAnyAccess('test', 'test1'));
        $this->assertTrue($permissions->hasAnyAccess(['test', 'test1']));
        $this->assertFalse($permissions->hasAnyAccess(['test4', 'test5']));

        $this->assertEquals($secondaryPermissions, $permissions->getSecondaryPermissions());
    }

    public function testWildCardPermissions()
    {
        $permissions = new PermissionsStub([
            'user.add'    => true,
            'user.remove' => false,
        ]);

        $this->assertTrue($permissions->hasAccess('user.*'));
    }

    public function testClassPermissions()
    {
        $permissions = new PermissionsStub([
            'Foo\Bar\Baz@add,view'      => true,
            'Foo\Bar\Baz@update,remove' => false,
        ]);

        $this->assertTrue($permissions->hasAccess('Foo\Bar\Baz@add'));
        $this->assertTrue($permissions->hasAccess('Foo\Bar\Baz@view'));

        $this->assertFalse($permissions->hasAccess('Foo\Bar\Baz@update'));
        $this->assertFalse($permissions->hasAccess('Foo\Bar\Baz@remove'));
    }
}

class PermissionsStub implements PermissionsInterface
{
    use PermissionsTrait;

    protected function createPreparedPermissions()
    {
        $prepared = [];

        if (! empty($this->secondaryPermissions)) {
            foreach ($this->secondaryPermissions as $permissions) {
                $this->preparePermissions($prepared, $permissions);
            }
        }

        if (! empty($this->permissions)) {
            $permissions = [];
            $this->preparePermissions($permissions, $this->permissions);
            $prepared = array_merge($prepared, $permissions);
        }

        return $prepared;
    }
}


text:
id: 60f5d2776c854e069560fbe6
title: Step 12
challengeType: 0
dashedName: step-12
---

# --description--

The first `fieldset` will hold name, email, and password fields. Start by adding four `label` elements to the first `fieldset`.

# --hints--

You should add four `label` elements.

```js
assert.equal(document.querySelectorAll('label')?.length, 4);
```

You should add the `label` elements to the first `fieldset`.

```js
assert.equal(document.querySelector('fieldset')?.querySelectorAll('label')?.length, 4);
```

# --seed--

## --seed-contents--

```html
<!DOCTYPE html>
<html>
  <head>
    <title>freeCodeCamp Registration Form Project</title>
	  <link rel="stylesheet" type="text/css" href="styles.css" />
  </head>
  <body>
    <h1>Registration Form</h1>
    <p>Please fill out this form with the required information</p>
--fcc-editable-region--
    <form action='https://fcc-registration-form.com'>
      <fieldset>

      </fieldset>
      <fieldset></fieldset>
      <fieldset></fieldset>
    </form>
--fcc-editable-region--
  </body>
</html>
```

```css
body {
  width: 100%;
  height: 100vh;
  margin: 0;
  background-color: #1b1b32;
	color: #f5f6f7;
}
```


text:
<?php
App::uses('AppModel', 'Model');
App::uses('GearmanQueue', 'Gearman.Client');
/**
 * Artist Model
 *
 * @property Song $Song
 */
class Artist extends AppModel {
/**
 * Display field
 *
 * @var string
 */
	public $displayField = 'name';
/**
 * Validation rules
 *
 * @var array
 */
	public $validate = array(
		'name' => array(
			'notempty' => array(
				'rule' => array('notempty'),
				//'message' => 'Your custom message here',
				//'allowEmpty' => false,
				//'required' => false,
				//'last' => false, // Stop validation after this rule
				//'on' => 'create', // Limit validation to 'create' or 'update' operations
			),
		),
	);

	//The Associations below have been created with all possible keys, those that are not needed can be removed

/**
 * hasAndBelongsToMany associations
 *
 * @var array
 */
	public $hasAndBelongsToMany = array(
		'Song' => array(
			'className' => 'Song',
			'joinTable' => 'artists_songs',
			'foreignKey' => 'artist_id',
			'associationForeignKey' => 'song_id',
			'unique' => true,
			'conditions' => '',
			'fields' => '',
			'order' => '',
			'limit' => '',
			'offset' => '',
			'finderQuery' => '',
			'deleteQuery' => '',
			'insertQuery' => ''
		)
	);

	public function getHot($limit = 50, $cached = true) {
		if (!is_int($limit)) {
			throw new Exception("Invalid limit");
		}

		if ($limit > 100) {
			throw new Exception("We were asked to get more entries than we could");
		}

		if ($cached) {
			$artists = Cache::read('hot_artists_'.$limit, '_hourly_');
			if ($artists !== false)
				return $artists;
			GearmanQueue::execute('getHotArtists', $limit);
			$artists = Cache::read('hot_artists_'.$limit, 'longterm');
			if ($artists !== false)
				return $artists;
			// Empty page until gearman proceses the above task
			return array();
		}

		$apidata = LastFM\Geo::getTopArtists("united states", 500);
		// 500 is a little hefty, but it should be okay for now

		$artists = array();
		foreach ($apidata as $artist) {
			if (count($artists) >= $limit) {
				break; // We have enough
			}
			$this->recursive = -1;
			$a = $this->findByName($artist->getName());
			if ($a) {
				$artists[] = array(
						'Artist' => $a['Artist'],
						'Song' => array(),
						'Art' => $artist->getImage(),
				);
			}
			// TODO: add a more fuzzy fallback or something
		}
		// Get top tracks for each artist
		$this->Song->recursive = 2;
		foreach ($artists as &$artist){
			$tracks = LastFM\Artist::getTopTracks($artist['Artist']['name']);
			foreach ($tracks as $track) {
				$song = $this->Song->findByArtist($track->getName(), $artist['Artist']['name']);
				if ($song)
					$artist['Song'][] = $song;
			}
		}

		Cache::write('hot_artists_'.$limit, $artists, '_hourly_');
		Cache::write('hot_artists_'.$limit, $artists, 'longterm');
		return $artists;
	}

}


text:
#ifndef WEBRTC_MODULES_VIDEO_CODING_FRAME_OBJECT_H_
#define WEBRTC_MODULES_VIDEO_CODING_FRAME_OBJECT_H_

#include "webrtc/common_types.h"
#include "webrtc/modules/include/module_common_types.h"
#include "webrtc/modules/video_coding/encoded_frame.h"

namespace webrtc {
namespace video_coding {

class FrameObject : public webrtc::VCMEncodedFrame {
 public:
  static const uint8_t kMaxFrameReferences = 5;

  FrameObject();
  virtual ~FrameObject() {}

  virtual bool GetBitstream(uint8_t* destination) const = 0;

  // The capture timestamp of this frame.
  virtual uint32_t Timestamp() const = 0;

  // When this frame was received.
  virtual int64_t ReceivedTime() const = 0;

  // When this frame should be rendered.
  virtual int64_t RenderTime() const = 0;

  size_t size() { return _length; }

  // The tuple (|picture_id|, |spatial_layer|) uniquely identifies a frame
  // object. For codec types that don't necessarily have picture ids they
  // have to be constructed from the header data relevant to that codec.
  uint16_t picture_id;
  uint8_t spatial_layer;
  uint32_t timestamp;

  size_t num_references;
  uint16_t references[kMaxFrameReferences];
  bool inter_layer_predicted;
};

class PacketBuffer;

class RtpFrameObject : public FrameObject {
 public:
  RtpFrameObject(PacketBuffer* packet_buffer,
                 uint16_t first_seq_num,
                 uint16_t last_seq_num,
                 size_t frame_size,
                 int times_nacked,
                 int64_t received_time);

  ~RtpFrameObject();
  uint16_t first_seq_num() const;
  uint16_t last_seq_num() const;
  int times_nacked() const;
  enum FrameType frame_type() const;
  VideoCodecType codec_type() const;
  bool GetBitstream(uint8_t* destination) const override;
  uint32_t Timestamp() const override;
  int64_t ReceivedTime() const override;
  int64_t RenderTime() const override;
  RTPVideoTypeHeader* GetCodecHeader() const;

 private:
  rtc::scoped_refptr<PacketBuffer> packet_buffer_;
  enum FrameType frame_type_;
  VideoCodecType codec_type_;
  uint16_t first_seq_num_;
  uint16_t last_seq_num_;
  uint32_t timestamp_;
  int64_t received_time_;

  // Equal to times nacked of the packet with the highet times nacked
  // belonging to this frame.
  int times_nacked_;
};

}  // namespace video_coding
}  // namespace webrtc

#endif  // WEBRTC_MODULES_VIDEO_CODING_FRAME_OBJECT_H_


text:
/* ----------------------------------------------------------------------------
 * This file was automatically generated by SWIG (http://www.swig.org).
 * Version 2.0.4
 *
 * Do not make changes to this file unless you know what you are doing--modify
 * the SWIG interface file instead.
 * ----------------------------------------------------------------------------- */

using System;
using System.Runtime.InteropServices;

namespace Noesis
{

public class GridViewHeaderRowPresenter : GridViewRowPresenterBase {
  internal new static GridViewHeaderRowPresenter CreateProxy(IntPtr cPtr, bool cMemoryOwn) {
    return new GridViewHeaderRowPresenter(cPtr, cMemoryOwn);
  }

  internal GridViewHeaderRowPresenter(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) {
  }

  internal static HandleRef getCPtr(GridViewHeaderRowPresenter obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  public GridViewHeaderRowPresenter() {
  }

  protected override System.IntPtr CreateCPtr(System.Type type, out bool registerExtend) {
    registerExtend = false;
    return NoesisGUI_PINVOKE.new_GridViewHeaderRowPresenter();
  }

  public static DependencyProperty AllowsColumnReorderProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_AllowsColumnReorderProperty_get();
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public static DependencyProperty ColumnHeaderContainerStyleProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderContainerStyleProperty_get();
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public static DependencyProperty ColumnHeaderContextMenuProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderContextMenuProperty_get();
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public static DependencyProperty ColumnHeaderStringFormatProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderStringFormatProperty_get();
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public static DependencyProperty ColumnHeaderTemplateProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderTemplateProperty_get();
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public static DependencyProperty ColumnHeaderTemplateSelectorProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderTemplateSelectorProperty_get();
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public static DependencyProperty ColumnHeaderToolTipProperty {
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderToolTipProperty_get();
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public bool AllowsColumnReorder {
    set {
      NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_AllowsColumnReorder_set(swigCPtr, value);
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
    }
    get {
      bool ret = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_AllowsColumnReorder_get(swigCPtr);
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return ret;
    }
  }

  public Style ColumnHeaderContainerStyle {
    set {
      NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderContainerStyle_set(swigCPtr, Style.getCPtr(value));
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
    }
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderContainerStyle_get(swigCPtr);
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (Style)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public ContextMenu ColumnHeaderContextMenu {
    set {
      NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderContextMenu_set(swigCPtr, ContextMenu.getCPtr(value));
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
    }
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderContextMenu_get(swigCPtr);
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (ContextMenu)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public string ColumnHeaderStringFormat {
    set {
      NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderStringFormat_set(swigCPtr, value != null ? value : string.Empty);
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
    }
    get {
      IntPtr strPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderStringFormat_get(swigCPtr);
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      string str = Noesis.Extend.StringFromNativeUtf8(strPtr);
      return str;
    }
  }

  public DataTemplate ColumnHeaderTemplate {
    set {
      NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderTemplate_set(swigCPtr, DataTemplate.getCPtr(value));
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
    }
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderTemplate_get(swigCPtr);
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (DataTemplate)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public DataTemplateSelector ColumnHeaderTemplateSelector {
    set {
      NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderTemplateSelector_set(swigCPtr, DataTemplateSelector.getCPtr(value));
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
    }
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderTemplateSelector_get(swigCPtr);
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return (DataTemplateSelector)Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  public object ColumnHeaderToolTip {
    set {
      NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderToolTip_set(swigCPtr, Noesis.Extend.GetInstanceHandle(value));
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
    }
    get {
      IntPtr cPtr = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_ColumnHeaderToolTip_get(swigCPtr);
      #if UNITY_EDITOR || NOESIS_API
      if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
      #endif
      return Noesis.Extend.GetProxy(cPtr, false);
    }
  }

  new internal static IntPtr GetStaticType() {
    IntPtr ret = NoesisGUI_PINVOKE.GridViewHeaderRowPresenter_GetStaticType();
    #if UNITY_EDITOR || NOESIS_API
    if (NoesisGUI_PINVOKE.SWIGPendingException.Pending) throw NoesisGUI_PINVOKE.SWIGPendingException.Retrieve();
    #endif
    return ret;
  }

}

}


text:
// Protocol Buffers for Go with Gadgets
//
// Copyright (c) 2013, The GoGo Authors. All rights reserved.
// http://github.com/gogo/protobuf
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package packed

import (
	"bytes"
	"fmt"
	math_rand "math/rand"
	"runtime"
	"testing"
	"time"
	"unsafe"

	"github.com/gogo/protobuf/proto"
)

func BenchmarkVarintIssue436withCount(b *testing.B) {
	var arraySizes = []struct {
		name  string
		value int64
	}{
		{"2^0_ints", 1 << 0},
		{"2^1_ints", 1 << 1},
		{"2^2_ints", 1 << 2},
		{"2^3_ints", 1 << 3},
		{"2^4_ints", 1 << 4},
		{"2^8_ints", 1 << 8},
		{"2^16_ints", 1 << 16},
		{"2^20_ints", 1 << 20},
		{"2^24_ints", 1 << 24},
	}

	var varintSizes = []struct {
		name  string
		value int64
	}{
		{"max_int 2^7-4", 1<<7 - 4},
		{"max_int 2^15-4", 1<<15 - 4},
		{"max_int 2^31-4", 1<<31 - 4},
		{"max_int 2^63-4", 1<<63 - 4},
	}

	for _, arraySize := range arraySizes {
		for _, varintSize := range varintSizes {
			seed := time.Now().UnixNano()
			rng := math_rand.New(math_rand.NewSource(seed))
			buf := make([]int64, arraySize.value)
			for j := range buf {
				buf[j] = rng.Int63n(varintSize.value)
			}

			b.Run(arraySize.name+", "+varintSize.name, func(b *testing.B) {
				msg := &NinRepNative{
					Field8: buf,
				}

				data, err := proto.Marshal(msg)
				if err != nil {
					b.Fatal(err)
				}

				normalmsg := &NinRepNative{}

				for i := 0; i < b.N; i++ {
					err = proto.Unmarshal(data, normalmsg)
					if err != nil {
						b.Fatal(err)
					}
				}
			})
		}
	}
}

func TestVarintIssue436(t *testing.T) {
	n := 1 << 22 // Makes for 32 MiB

	m := &runtime.MemStats{}

	msgNormal := &NinRepNative{
		Field8: make([]int64, n),
	}
	dataNormal, err := proto.Marshal(msgNormal)
	if err != nil {
		t.Fatal(err)
	}

	normalmsg := &NinRepNative{}
	runtime.ReadMemStats(m)
	beforeNormal := m.TotalAlloc
	err = proto.Unmarshal(dataNormal, normalmsg)
	runtime.ReadMemStats(m)
	afterNormal := m.TotalAlloc
	if err != nil {
		t.Fatal(err)
	}

	msgPacked := &NinRepPackedNative{
		Field8: make([]int64, n),
	}
	dataPacked, err := proto.Marshal(msgPacked)
	if err != nil {
		t.Fatal(err)
	}

	packedmsg := &NinRepPackedNative{}
	runtime.ReadMemStats(m)
	beforePacked := m.TotalAlloc
	err = proto.Unmarshal(dataPacked, packedmsg)
	runtime.ReadMemStats(m)
	afterPacked := m.TotalAlloc
	if err != nil {
		t.Fatal(err)
	}

	totalNormal := afterNormal - beforeNormal
	totalPacked := afterPacked - beforePacked
	usedRatio := float64(totalPacked) / float64(totalNormal)
	if usedRatio > 0.5 {
		t.Fatalf("unmarshaling packed msg allocated too much memory:\nnormal:\t\t%d bytes\npacked:\t\t%d bytes\nused ratio:\t%.2f%%", totalNormal, totalPacked, usedRatio*100)
	}
}

func TestIssue436(t *testing.T) {
	n := 1 << 22 // Makes for 32 MiB

	m := &runtime.MemStats{}

	msgNormal := &NinRepNative{
		Field1: make([]float64, n),
	}
	dataNormal, err := proto.Marshal(msgNormal)
	if err != nil {
		t.Fatal(err)
	}

	normalmsg := &NinRepNative{}
	runtime.ReadMemStats(m)
	beforeNormal := m.TotalAlloc
	err = proto.Unmarshal(dataNormal, normalmsg)
	runtime.ReadMemStats(m)
	afterNormal := m.TotalAlloc
	if err != nil {
		t.Fatal(err)
	}

	msgPacked := &NinRepPackedNative{
		Field1: make([]float64, n),
	}
	dataPacked, err := proto.Marshal(msgPacked)
	if err != nil {
		t.Fatal(err)
	}

	packedmsg := &NinRepPackedNative{}
	runtime.ReadMemStats(m)
	beforePacked := m.TotalAlloc
	err = proto.Unmarshal(dataPacked, packedmsg)
	runtime.ReadMemStats(m)
	afterPacked := m.TotalAlloc
	if err != nil {
		t.Fatal(err)
	}

	totalNormal := afterNormal - beforeNormal
	totalPacked := afterPacked - beforePacked
	usedRatio := float64(totalPacked) / float64(totalNormal)
	if usedRatio > 0.5 {
		t.Fatalf("unmarshaling packed msg allocated too much memory:\nnormal:\t\t%d bytes\npacked:\t\t%d bytes\nused ratio:\t%.2f%%", totalNormal, totalPacked, usedRatio*100)
	}
}

/*
https://github.com/gogo/protobuf/issues/503
preallocation was estimating length over all data vs. just that for the given field.
*/
func TestTestPackedPreallocation(t *testing.T) {
	n1 := 900
	n2 := 700

	msgPacked := &NinRepPackedNative{
		Field3: make([]int32, n1),
		Field4: make([]int64, n2),
	}

	dataPacked, err := proto.Marshal(msgPacked)
	if err != nil {
		t.Fatal(err)
	}

	packedmsg := &NinRepPackedNative{}
	err = proto.Unmarshal(dataPacked, packedmsg)
	if err != nil {
		t.Fatal(err)
	}

	if v := len(packedmsg.Field3); v != n1 {
		t.Errorf("Field3 incorrect len: %v != %v", v, n1)
	}

	if v := len(packedmsg.Field4); v != n2 {
		t.Errorf("Field4 incorrect len: %v != %v", v, n2)
	}

	if v := cap(packedmsg.Field3); v != n1 {
		t.Errorf("Field3 incorrect cap: %v != %v", v, n1)
	}

	if v := cap(packedmsg.Field4); v != n2 {
		t.Errorf("Field4 incorrect cap: %v != %v", v, n2)
	}
}

/*
https://github.com/gogo/protobuf/issues/detail?id=21
https://developers.google.com/protocol-buffers/docs/proto#options
In 2.3.0 and later, this change is safe, as parsers for packable fields will always accept both formats,
*/
func TestSafeIssue21(t *testing.T) {
	popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
	msg1 := NewPopulatedNinRepNative(popr, true)
	data1, err := proto.Marshal(msg1)
	if err != nil {
		t.Fatal(err)
	}
	packedmsg := &NinRepPackedNative{}
	err = proto.Unmarshal(data1, packedmsg)
	if err != nil {
		t.Fatal(err)
	}
	if len(packedmsg.XXX_unrecognized) != 0 {
		t.Fatalf("packed msg unmarshaled unrecognized fields, even though there aren't any")
	}
	if err := VerboseEqual(msg1, packedmsg); err != nil {
		t.Fatalf("%v", err)
	}
}

func TestUnsafeIssue21(t *testing.T) {
	var bigendian uint32 = 0x01020304
	if *(*byte)(unsafe.Pointer(&bigendian)) == 1 {
		t.Skip("unsafe does not work on big endian architectures")
	}
	popr := math_rand.New(math_rand.NewSource(time.Now().UnixNano()))
	msg1 := NewPopulatedNinRepNativeUnsafe(popr, true)
	data1, err := proto.Marshal(msg1)
	if err != nil {
		t.Fatal(err)
	}
	packedmsg := &NinRepPackedNativeUnsafe{}
	err = proto.Unmarshal(data1, packedmsg)
	if err != nil {
		t.Fatal(err)
	}
	if len(packedmsg.XXX_unrecognized) != 0 {
		t.Fatalf("packed msg unmarshaled unrecognized fields, even though there aren't any")
	}
	if err := VerboseEqualUnsafe(msg1, packedmsg); err != nil {
		t.Fatalf("%v", err)
	}
}

func VerboseEqual(this *NinRepNative, that *NinRepPackedNative) error {
	if that == nil {
		if this == nil {
			return nil
		}
		return fmt.Errorf("that == nil && this != nil")
	} else if this == nil {
		return fmt.Errorf("that != nil && this == nil")
	}

	if len(this.Field1) != len(that.Field1) {
		return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", len(this.Field1), len(that.Field1))
	}
	for i := range this.Field1 {
		if this.Field1[i] != that.Field1[i] {
			return fmt.Errorf("Field1 this[%v](%v) Not Equal that[%v](%v)", i, this.Field1[i], i, that.Field1[i])
		}
	}
	if len(this.Field2) != len(that.Field2) {
		return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", len(this.Field2), len(that.Field2))
	}
	for i := range this.Field2 {
		if this.Field2[i] != that.Field2[i] {
			return fmt.Errorf("Field2 this[%v](%v) Not Equal that[%v](%v)", i, this.Field2[i], i, that.Field2[i])
		}
	}
	if len(this.Field3) != len(that.Field3) {
		return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", len(this.Field3), len(that.Field3))
	}
	for i := range this.Field3 {
		if this.Field3[i] != that.Field3[i] {
			return fmt.Errorf("Field3 this[%v](%v) Not Equal that[%v](%v)", i, this.Field3[i], i, that.Field3[i])
		}
	}
	if len(this.Field4) != len(that.Field4) {
		return fmt.Errorf("Field4 this(%v) Not Equal that(%v)", len(this.Field4), len(that.Field4))
	}
	for i := range this.Field4 {
		if this.Field4[i] != that.Field4[i] {
			return fmt.Errorf("Field4 this[%v](%v) Not Equal that[%v](%v)", i, this.Field4[i], i, that.Field4[i])
		}
	}
	if len(this.Field5) != len(that.Field5) {
		return fmt.Errorf("Field5 this(%v) Not Equal that(%v)", len(this.Field5), len(that.Field5))
	}
	for i := range this.Field5 {
		if this.Field5[i] != that.Field5[i] {
			return fmt.Errorf("Field5 this[%v](%v) Not Equal that[%v](%v)", i, this.Field5[i], i, that.Field5[i])
		}
	}
	if len(this.Field6) != len(that.Field6) {
		return fmt.Errorf("Field6 this(%v) Not Equal that(%v)", len(this.Field6), len(that.Field6))
	}
	for i := range this.Field6 {
		if this.Field6[i] != that.Field6[i] {
			return fmt.Errorf("Field6 this[%v](%v) Not Equal that[%v](%v)", i, this.Field6[i], i, that.Field6[i])
		}
	}
	if len(this.Field7) != len(that.Field7) {
		return fmt.Errorf("Field7 this(%v) Not Equal that(%v)", len(this.Field7), len(that.Field7))
	}
	for i := range this.Field7 {
		if this.Field7[i] != that.Field7[i] {
			return fmt.Errorf("Field7 this[%v](%v) Not Equal that[%v](%v)", i, this.Field7[i], i, that.Field7[i])
		}
	}
	if len(this.Field8) != len(that.Field8) {
		return fmt.Errorf("Field8 this(%v) Not Equal that(%v)", len(this.Field8), len(that.Field8))
	}
	for i := range this.Field8 {
		if this.Field8[i] != that.Field8[i] {
			return fmt.Errorf("Field8 this[%v](%v) Not Equal that[%v](%v)", i, this.Field8[i], i, that.Field8[i])
		}
	}
	if len(this.Field9) != len(that.Field9) {
		return fmt.Errorf("Field9 this(%v) Not Equal that(%v)", len(this.Field9), len(that.Field9))
	}
	for i := range this.Field9 {
		if this.Field9[i] != that.Field9[i] {
			return fmt.Errorf("Field9 this[%v](%v) Not Equal that[%v](%v)", i, this.Field9[i], i, that.Field9[i])
		}
	}
	if len(this.Field10) != len(that.Field10) {
		return fmt.Errorf("Field10 this(%v) Not Equal that(%v)", len(this.Field10), len(that.Field10))
	}
	for i := range this.Field10 {
		if this.Field10[i] != that.Field10[i] {
			return fmt.Errorf("Field10 this[%v](%v) Not Equal that[%v](%v)", i, this.Field10[i], i, that.Field10[i])
		}
	}
	if len(this.Field11) != len(that.Field11) {
		return fmt.Errorf("Field11 this(%v) Not Equal that(%v)", len(this.Field11), len(that.Field11))
	}
	for i := range this.Field11 {
		if this.Field11[i] != that.Field11[i] {
			return fmt.Errorf("Field11 this[%v](%v) Not Equal that[%v](%v)", i, this.Field11[i], i, that.Field11[i])
		}
	}
	if len(this.Field12) != len(that.Field12) {
		return fmt.Errorf("Field12 this(%v) Not Equal that(%v)", len(this.Field12), len(that.Field12))
	}
	for i := range this.Field12 {
		if this.Field12[i] != that.Field12[i] {
			return fmt.Errorf("Field12 this[%v](%v) Not Equal that[%v](%v)", i, this.Field12[i], i, that.Field12[i])
		}
	}
	if len(this.Field13) != len(that.Field13) {
		return fmt.Errorf("Field13 this(%v) Not Equal that(%v)", len(this.Field13), len(that.Field13))
	}
	for i := range this.Field13 {
		if this.Field13[i] != that.Field13[i] {
			return fmt.Errorf("Field13 this[%v](%v) Not Equal that[%v](%v)", i, this.Field13[i], i, that.Field13[i])
		}
	}
	if !bytes.Equal(this.XXX_unrecognized, that.XXX_unrecognized) {
		return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that.XXX_unrecognized)
	}
	return nil
}

func VerboseEqualUnsafe(this *NinRepNativeUnsafe, that *NinRepPackedNativeUnsafe) error {
	if that == nil {
		if this == nil {
			return nil
		}
		return fmt.Errorf("that == nil && this != nil")
	} else if this == nil {
		return fmt.Errorf("that != nil && this == nil")
	}

	if len(this.Field1) != len(that.Field1) {
		return fmt.Errorf("Field1 this(%v) Not Equal that(%v)", len(this.Field1), len(that.Field1))
	}
	for i := range this.Field1 {
		if this.Field1[i] != that.Field1[i] {
			return fmt.Errorf("Field1 this[%v](%v) Not Equal that[%v](%v)", i, this.Field1[i], i, that.Field1[i])
		}
	}
	if len(this.Field2) != len(that.Field2) {
		return fmt.Errorf("Field2 this(%v) Not Equal that(%v)", len(this.Field2), len(that.Field2))
	}
	for i := range this.Field2 {
		if this.Field2[i] != that.Field2[i] {
			return fmt.Errorf("Field2 this[%v](%v) Not Equal that[%v](%v)", i, this.Field2[i], i, that.Field2[i])
		}
	}
	if len(this.Field3) != len(that.Field3) {
		return fmt.Errorf("Field3 this(%v) Not Equal that(%v)", len(this.Field3), len(that.Field3))
	}
	for i := range this.Field3 {
		if this.Field3[i] != that.Field3[i] {
			return fmt.Errorf("Field3 this[%v](%v) Not Equal that[%v](%v)", i, this.Field3[i], i, that.Field3[i])
		}
	}
	if len(this.Field4) != len(that.Field4) {
		return fmt.Errorf("Field4 this(%v) Not Equal that(%v)", len(this.Field4), len(that.Field4))
	}
	for i := range this.Field4 {
		if this.Field4[i] != that.Field4[i] {
			return fmt.Errorf("Field4 this[%v](%v) Not Equal that[%v](%v)", i, this.Field4[i], i, that.Field4[i])
		}
	}
	if len(this.Field5) != len(that.Field5) {
		return fmt.Errorf("Field5 this(%v) Not Equal that(%v)", len(this.Field5), len(that.Field5))
	}
	for i := range this.Field5 {
		if this.Field5[i] != that.Field5[i] {
			return fmt.Errorf("Field5 this[%v](%v) Not Equal that[%v](%v)", i, this.Field5[i], i, that.Field5[i])
		}
	}
	if len(this.Field6) != len(that.Field6) {
		return fmt.Errorf("Field6 this(%v) Not Equal that(%v)", len(this.Field6), len(that.Field6))
	}
	for i := range this.Field6 {
		if this.Field6[i] != that.Field6[i] {
			return fmt.Errorf("Field6 this[%v](%v) Not Equal that[%v](%v)", i, this.Field6[i], i, that.Field6[i])
		}
	}
	if len(this.Field7) != len(that.Field7) {
		return fmt.Errorf("Field7 this(%v) Not Equal that(%v)", len(this.Field7), len(that.Field7))
	}
	for i := range this.Field7 {
		if this.Field7[i] != that.Field7[i] {
			return fmt.Errorf("Field7 this[%v](%v) Not Equal that[%v](%v)", i, this.Field7[i], i, that.Field7[i])
		}
	}
	if len(this.Field8) != len(that.Field8) {
		return fmt.Errorf("Field8 this(%v) Not Equal that(%v)", len(this.Field8), len(that.Field8))
	}
	for i := range this.Field8 {
		if this.Field8[i] != that.Field8[i] {
			return fmt.Errorf("Field8 this[%v](%v) Not Equal that[%v](%v)", i, this.Field8[i], i, that.Field8[i])
		}
	}
	if len(this.Field9) != len(that.Field9) {
		return fmt.Errorf("Field9 this(%v) Not Equal that(%v)", len(this.Field9), len(that.Field9))
	}
	for i := range this.Field9 {
		if this.Field9[i] != that.Field9[i] {
			return fmt.Errorf("Field9 this[%v](%v) Not Equal that[%v](%v)", i, this.Field9[i], i, that.Field9[i])
		}
	}
	if len(this.Field10) != len(that.Field10) {
		return fmt.Errorf("Field10 this(%v) Not Equal that(%v)", len(this.Field10), len(that.Field10))
	}
	for i := range this.Field10 {
		if this.Field10[i] != that.Field10[i] {
			return fmt.Errorf("Field10 this[%v](%v) Not Equal that[%v](%v)", i, this.Field10[i], i, that.Field10[i])
		}
	}
	if len(this.Field11) != len(that.Field11) {
		return fmt.Errorf("Field11 this(%v) Not Equal that(%v)", len(this.Field11), len(that.Field11))
	}
	for i := range this.Field11 {
		if this.Field11[i] != that.Field11[i] {
			return fmt.Errorf("Field11 this[%v](%v) Not Equal that[%v](%v)", i, this.Field11[i], i, that.Field11[i])
		}
	}
	if len(this.Field12) != len(that.Field12) {
		return fmt.Errorf("Field12 this(%v) Not Equal that(%v)", len(this.Field12), len(that.Field12))
	}
	for i := range this.Field12 {
		if this.Field12[i] != that.Field12[i] {
			return fmt.Errorf("Field12 this[%v](%v) Not Equal that[%v](%v)", i, this.Field12[i], i, that.Field12[i])
		}
	}
	if len(this.Field13) != len(that.Field13) {
		return fmt.Errorf("Field13 this(%v) Not Equal that(%v)", len(this.Field13), len(that.Field13))
	}
	for i := range this.Field13 {
		if this.Field13[i] != that.Field13[i] {
			return fmt.Errorf("Field13 this[%v](%v) Not Equal that[%v](%v)", i, this.Field13[i], i, that.Field13[i])
		}
	}
	if !bytes.Equal(this.XXX_unrecognized, that.XXX_unrecognized) {
		return fmt.Errorf("XXX_unrecognized this(%v) Not Equal that(%v)", this.XXX_unrecognized, that.XXX_unrecognized)
	}
	return nil
}


text:
#ifndef BASE_H
#define BASE_H

class Base {
  public:
    virtual void method1(const char* param);
};

#endif /* BASE_H */


text:
require 'rails_helper'

RSpec.describe Api::V1::ConversionService do
  describe 'boolean_to_yes_no_unknown' do
    it 'returns `yes` when true' do
      expect(described_class.boolean_to_yes_no_unknown(true)).to eql('yes')
    end
    it 'returns `yes` when 1' do
      expect(described_class.boolean_to_yes_no_unknown(1)).to eql('yes')
    end
    it 'returns `no` when false' do
      expect(described_class.boolean_to_yes_no_unknown(false)).to eql('no')
    end
    it 'returns `no` when 0' do
      expect(described_class.boolean_to_yes_no_unknown(0)).to eql('no')
    end
    it 'returns `unknown` when nil' do
      expect(described_class.boolean_to_yes_no_unknown(nil)).to eql('unknown')
    end
  end

  describe 'yes_no_unknown_to_boolean' do
    it 'returns true when `yes`' do
      expect(described_class.yes_no_unknown_to_boolean('yes')).to eql(true)
    end
    it 'returns false when `no`' do
      expect(described_class.yes_no_unknown_to_boolean('no')).to eql(false)
    end
    it 'returns nil when `unknown`' do
      expect(described_class.yes_no_unknown_to_boolean('unknown')).to eql(nil)
    end
  end

  describe '#to_identifier(context:, value:)' do
    it 'returns nil if the context is not present' do
      expected = described_class.to_identifier(context: nil,
                                               value: Faker::Lorem.word)
      expect(expected).to eql(nil)
    end
    it 'returns nil if the value is not present' do
      expected = described_class.to_identifier(context: Faker::Lorem.word,
                                               value: nil)
      expect(expected).to eql(nil)
    end
    it 'returns an Identifier with a IdentifierScheme matching the context' do
      context = Faker::Lorem.word
      expected = described_class.to_identifier(context: context,
                                               value: Faker::Lorem.word)
      expect(expected.identifier_scheme.name).to eql(context)
    end
    it "returns an Identifier asssociated with the 'grant' scheme" do
      value = Faker::Lorem.word
      expected = described_class.to_identifier(context: Faker::Lorem.word,
                                               value: value)
      expect(expected.value).to eql(value)
    end
  end
end


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Shared data between oobe and the login screens. These files
 * are *not* used in the lock screen. If a file should also be used in the lock
 * screen, added it to login_shared.js.
 */

<include src="network_dropdown.js">

<include src="oobe_screen_reset_confirmation_overlay.js">
<include src="oobe_screen_reset.js">
<include src="oobe_screen_autolaunch.js">
<include src="oobe_screen_enable_kiosk.js">
<include src="oobe_screen_terms_of_service.js">
<include src="oobe_screen_user_image.js">

<include src="screen_app_launch_splash.js">
<include src="screen_error_message.js">
<include src="screen_gaia_signin.js">
<include src="screen_password_changed.js">
<include src="screen_supervised_user_creation.js">
<include src="screen_tpm_error.js">
<include src="screen_wrong_hwid.js">
<include src="screen_confirm_password.js">
<include src="screen_fatal_error.js">
<include src="screen_device_disabled.js">
<include src="screen_unrecoverable_cryptohome_error.js">

// Register assets for async loading.
[{
  id: SCREEN_OOBE_ENROLLMENT,
  html: [{ url: 'chrome://oobe/enrollment.html', targetID: 'inner-container' }],
  css: ['chrome://oobe/enrollment.css'],
  js: ['chrome://oobe/enrollment.js']
}].forEach(cr.ui.login.ResourceLoader.registerAssets);

(function() {
  'use strict';

  document.addEventListener('DOMContentLoaded', function() {
    // Immediately load async assets.
    // TODO(dconnelly): remove this at some point and only load as needed.
    // See crbug.com/236426
    cr.ui.login.ResourceLoader.loadAssets(SCREEN_OOBE_ENROLLMENT, function() {
      // This screen is async-loaded so we manually trigger i18n processing.
      i18nTemplate.process($('oauth-enrollment'), loadTimeData);
      // Delayed binding since this isn't defined yet.
      login.OAuthEnrollmentScreen.register();
    });
  });
})();


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

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>DontImportSunRule xref</title>
<link type="text/css" rel="stylesheet" href="../../../../../../../stylesheet.css" />

View Javadoc

1   package net.sourceforge.pmd.lang.java.rule.controversial;
2
3   import net.sourceforge.pmd.lang.java.ast.ASTImportDeclaration;
4   import net.sourceforge.pmd.lang.java.rule.AbstractJavaRule;
5
6   public class DontImportSunRule extends AbstractJavaRule {
7
8       public Object visit(ASTImportDeclaration node, Object data) {
9           String img = node.jjtGetChild(0).getImage();
10          if (img.startsWith("sun.") && !img.startsWith("sun.misc.Signal")) {
11              addViolation(data, node);
12          }
13          return data;
14      }
15
16  }

This page was automatically generated by Maven


text:
/**
 * This class uses `Ext.draw.sprite.Sprite` to render the chart legend.
 */
Ext.define('Ext.chart.legend.SpriteLegend', {
    alias: 'legend.sprite',
    type: 'sprite',
    isLegend: true,
    isSpriteLegend: true,

    requires: [
        'Ext.chart.legend.sprite.Item',
        'Ext.chart.legend.sprite.Border',
        'Ext.draw.overrides.hittest.All',
        'Ext.draw.Animator'
    ],

    config: {
        /**
         * @cfg {String} [docked='bottom']
         * The position of the legend in the chart.
         * Possible values: 'bottom' (default), 'top', 'left', 'right'.
         */
        docked: 'bottom',

        /**
         * @cfg {Ext.chart.legend.store.Store} store
         * The {@link Ext.chart.legend.store.Store} to bind this legend to.
         */
        store: 'ext-empty-store',

        /**
         * @cfg {Ext.chart.AbstractChart} chart
         * The chart that the store belongs to.
         */
        chart: null,

        /**
         * @protected
         * @cfg {Ext.draw.Surface} surface
         * The chart surface used to render legend sprites.
         */
        surface: null,

        /**
         * @readonly
         * The size of the area occupied by legend sprites.
         * This is set by the legend itself and then used during chart layout
         * to make sure the 'legend' surface is big enough to accommodate
         * legend sprites.
         */
        size: {
            width: 0,
            height: 0
        },

        /**
         * @cfg {Boolean} [toggleable=true]
         * `true` to allow series items to have their visibility
         * toggled by interaction with the legend items.
         */
        toggleable: true,

        /**
         * @cfg {Number} [padding=10]
         * The padding amount between legend items and legend border.
         */
        padding: 10,

        label: {
            preciseMeasurement: true
        },

        marker: {
        },

        /**
         * @cfg {Object} border
         * The border that goes around legend item sprites.
         * The type of the sprite is determined by this config,
         * while the styling comes from a theme {@link Ext.chart.theme.Base #legend}.
         * If both this config and the theme provide values for the
         * same configs, the values from this config are used.
         * The sprite class used a legend border should have the `isLegendBorder`
         * property set to true on the prototype. The legend border sprite
         * should also have the `x`, `y`, `width` and `height` attributes
         * that determine it's position and dimensions.
         */
        border: {
            $value: {
                type: 'legendborder'
            },
            // The config should be processed at the time of the 'getSprites' call,
            // when we already have the legend surface, otherwise the border sprite
            // will not be added to the surface.
            lazy: true
        },

        /**
         * @cfg {Object} background Set the legend background.
         * This can be a gradient object, image, or color. This config works similarly
         * to the {@link Ext.chart.AbstractChart#background} config.
         */
        background: null
    },

    sprites: null,

    spriteZIndexes: {
        background: 0,
        border: 1,
        // Item sprites should have a higher zIndex than border,
        // or they won't react to clicks.
        item: 2
    },

    oldSize: {
        width: 0,
        height: 0
    },

    constructor: function (config) {
        this.initConfig(config);
    },

    applyStore: function (store) {
        return store && Ext.StoreManager.lookup(store);
    },

    applyBorder: function (config) {
        var border;

        if (config) {
            if (config.isSprite) {
                border = config;
            } else {
                border = Ext.create('sprite.' + config.type, config);
            }
        }
        if (border) {
            border.isLegendBorder = true;
            border.setAttributes({
                zIndex: this.spriteZIndexes.border
            });
        }

        return border;
    },

    updateBorder: function (border, oldBorder) {
        var surface = this.getSurface();

        this.borderSprite = null;
        if (surface) {
            if (oldBorder) {
                surface.remove(oldBorder);
            }
            if (border) {
                this.borderSprite = surface.add(border);
            }
        }
    },

    scheduleLayout: function () {
        if (!this.scheduledLayoutId) {
            this.scheduledLayoutId = Ext.draw.Animator.schedule('performLayout', this);
        }
    },

    cancelLayout: function () {
        Ext.draw.Animator.cancel(this.scheduledLayoutId);
        this.scheduledLayoutId = null;
    },

    performLayout: function () {
        var me = this,
            size = me.getSize(),
            gap = me.getPadding(),
            sprites = me.getSprites(),
            surface = me.getSurface(),
            background = me.getBackground(),
            surfaceRect = surface.getRect(),
            store = me.getStore(),
            ln = (sprites && sprites.length) || 0,
            result = true,
            i, sprite;

        if (!surface || !surfaceRect || !store) {
            return false;
        }

        me.cancelLayout();

        var docked = me.getDocked(),
            surfaceWidth = surfaceRect[2],
            surfaceHeight = surfaceRect[3],
            border = me.borderSprite,
            bboxes = [],
            startX,      // Coordinates of the top-left corner.
            startY,      // of the first 'legenditem' sprite.
            columnSize,  // Number of items in a column.
            columnCount, // Number of columns.
            columnWidth,
            itemsWidth,
            itemsHeight,
            paddedItemsWidth,  // The horizontal span of all 'legenditem' sprites.
            paddedItemsHeight, // The vertical span of all 'legenditem' sprites.
            paddedBorderWidth,
            paddedBorderHeight,
            itemHeight,
            bbox, x, y;

        for (i = 0; i < ln; i++) {
            sprite = sprites[i];
            bbox = sprite.getBBox();
            bboxes.push(bbox);
        }

        if (bbox) {
            itemHeight = bbox.height;
        }

        switch (docked) {
            /*

             Horizontal legend.
             The outer box is the legend surface.
             The inner box is the legend border.
             There's a fixed amount of padding between all the items,
             denoted by ##. This amount is controlled by the 'padding' config
             of the legend.

             |-------------------------------------------------------------|
             |                             ##                              |
             |    |---------------------------------------------------|    |
             |    |        ##              ##               ##        |    |
             |    |     --------        -----------      --------     |    |
             | ## | ## | Item 0 |   ## | Item 2    | ## | Item 4 | ## | ## |
             |    |     --------        -----------      --------     |    |
             |    |        ##              ##               ##        |    |
             |    |     ----------      ---------                     |    |
             |    | ## | Item 1   | ## | Item 3  |                    |    |
             |    |     ----------      ---------                     |    |
             |    |        ##              ##                         |    |
             |    |---------------------------------------------------|    |
             |                             ##                              |
             |-------------------------------------------------------------|

             */
            case 'bottom':
            case 'top':

                // surface must have a width before we can proceed to layout top/bottom
                // docked legend.  width may be 0 if we are rendered into an inactive tab.
                // see https://sencha.jira.com/browse/EXTJS-22454
                if (!surfaceWidth) {
                    return false;
                }

                columnSize = 0;

                // Split legend items into columns until the width is suitable.
                do {
                    itemsWidth = 0;
                    columnWidth = 0;
                    columnCount = 0;

                    columnSize++;

                    for (i = 0; i < ln; i++) {
                        bbox = bboxes[i];
                        if (bbox.width > columnWidth) {
                            columnWidth = bbox.width;
                        }
                        if ((i + 1) % columnSize === 0) {
                            itemsWidth += columnWidth;
                            columnWidth = 0;
                            columnCount++;
                        }
                    }
                    if (i % columnSize !== 0) {
                        itemsWidth += columnWidth;
                        columnCount++;
                    }
                    paddedItemsWidth = itemsWidth + (columnCount - 1) * gap;
                    paddedBorderWidth = paddedItemsWidth + gap * 4;

                } while (paddedBorderWidth > surfaceWidth);

                paddedItemsHeight = itemHeight * columnSize + (columnSize - 1) * gap;

                break;

            /*

             Vertical legend.

             |-----------------------------------------------|
             |                     ##                        |
             |    |-------------------------------------|    |
             |    |        ##               ##          |    |
             |    |     --------        -----------     |    |
             |    | ## | Item 0 |   ## | Item 1    | ## |    |
             |    |     --------        -----------     |    |
             |    |        ##               ##          |    |
             |    |     ----------      ---------       |    |
             | ## | ## | Item 2   | ## | Item 3  |      | ## |
             |    |     ----------      ---------       |    |
             |    |        ##                           |    |
             |    |     --------                        |    |
             |    | ## | Item 4 |                       |    |
             |    |     --------                        |    |
             |    |        ##                           |    |
             |    |-------------------------------------|    |
             |                     ##                        |
             |-----------------------------------------------|

             */

            case 'right':
            case 'left':

                // surface must have a height before we can proceed to layout right/left
                // docked legend.  height may be 0 if we are rendered into an inactive tab.
                // see https://sencha.jira.com/browse/EXTJS-22454
                if (!surfaceHeight) {
                    return false;
                }

                columnSize = ln * 2;

                // Split legend items into columns until the height is suitable.
                do {
                    // Integer division by 2, plus remainder.
                    columnSize = (columnSize >> 1) + (columnSize % 2);

                    itemsWidth = 0;
                    itemsHeight = 0;
                    columnWidth = 0;
                    columnCount = 0;

                    for (i = 0; i < ln; i++) {
                        bbox = bboxes[i];
                        // itemsHeight is determined by the height of the first column.
                        if (!columnCount) {
                            itemsHeight += bbox.height;
                        }
                        if (bbox.width > columnWidth) {
                            columnWidth = bbox.width;
                        }
                        if ((i + 1) % columnSize === 0) {
                            itemsWidth += columnWidth;
                            columnWidth = 0;
                            columnCount++;
                        }
                    }
                    if (i % columnSize !== 0) {
                        itemsWidth += columnWidth;
                        columnCount++;
                    }
                    paddedItemsWidth = itemsWidth + (columnCount - 1) * gap;
                    paddedItemsHeight = itemsHeight + (columnSize - 1) * gap;
                    paddedBorderWidth = paddedItemsWidth + gap * 4;
                    paddedBorderHeight = paddedItemsHeight + gap * 4;

                } while (paddedItemsHeight > surfaceHeight);

                break;

        }

        startX = (surfaceWidth - paddedItemsWidth) / 2;
        startY = (surfaceHeight - paddedItemsHeight) / 2;

        x = 0;
        y = 0;
        columnWidth = 0;

        for (i = 0; i < ln; i++) {
            sprite = sprites[i];
            bbox = bboxes[i];
            sprite.setAttributes({
                translationX: startX + x,
                translationY: startY + y
            });
            if (bbox.width > columnWidth) {
                columnWidth = bbox.width;
            }
            if ((i + 1) % columnSize === 0) {
                x += columnWidth + gap;
                y = 0;
                columnWidth = 0;
            } else {
                y += bbox.height + gap;
            }
        }

        if (border) {
            border.setAttributes({
                x: startX - gap,
                y: startY - gap,
                width: paddedItemsWidth + gap * 2,
                height: paddedItemsHeight + gap * 2
            });
        }

        size.width = border.attr.width + gap * 2;
        size.height = border.attr.height + gap * 2;

        if (size.width !== me.oldSize.width || size.height !== me.oldSize.height) {
            // Do not simply assign size to oldSize, as we want them to be
            // separate objects.
            Ext.apply(me.oldSize, size);
            // Legend size has changed, so we return 'false' to cancel the current
            // chart layout (this method is called by chart's 'performLayout' method)
            // and manually start a new chart layout.
            result = false;
            me.getChart().performLayout();
        }

        Ext.apply(me.oldSize, size);

        if (background) {
            me.resizeBackground(surface, background);
        }

        surface.renderFrame();

        return result;
    },

    // Doesn't include the border sprite which also belongs to the 'legend'
    // surface. To get it, use the 'getBorder' method.
    getSprites: function () {
        this.updateSprites();
        return this.sprites;
    },

    /**
     * @private
     * Creates a 'legenditem' sprite in the given surface
     * using the legend store record data provided.
     * @param {Ext.draw.Surface} surface
     * @param {Ext.chart.legend.store.Item} record
     * @return {Ext.chart.legend.sprite.Item}
     */
    createSprite: function (surface, record) {
        var me = this,
            data = record.data,
            chart = me.getChart(),
            series = chart.get(data.series),
            seriesMarker = series.getMarker(),
            sprite = null,
            markerConfig, labelConfig, legendItemConfig;

        if (surface) {
            markerConfig = series.getMarkerStyleByIndex(data.index);
            Ext.apply(markerConfig, me.getMarker());
            if (seriesMarker && seriesMarker.type && !markerConfig.type) {
                markerConfig.type = seriesMarker.type;
            }
            labelConfig = me.getLabel();

            legendItemConfig = {
                type: 'legenditem',
                zIndex: me.spriteZIndexes.item,
                text: data.name,
                enabled: !data.disabled,
                marker: markerConfig,
                label: labelConfig,
                series: data.series,
                record: record
            };

            sprite = surface.add(legendItemConfig);
        }

        return sprite;
    },

    /**
     * @private
     * Creates legend item sprites and associates them with legend store records.
     * Updates attributes of the sprites when legend store data changes.
     */
    updateSprites: function () {
        var me = this,
            chart = me.getChart(),
            store = me.getStore(),
            surface = me.getSurface(),
            item, items, itemSprite,
            i, ln, sprites, unusedSprites,
            border;

        if (!(chart && store && surface)) {
            return;
        }

        me.sprites = sprites = me.sprites || [];
        items = store.getData().items;
        ln = items.length;

        for (i = 0; i < ln; i++) {
            item = items[i];
            itemSprite = sprites[i];
            if (itemSprite) {
                me.updateSprite(itemSprite, item);
            } else {
                itemSprite = me.createSprite(surface, item);
                surface.add(itemSprite);
                sprites.push(itemSprite);
            }
        }

        unusedSprites = Ext.Array.splice(sprites, i, sprites.length);
        for (i = 0, ln = unusedSprites.length; i < ln; i++) {
            itemSprite = unusedSprites[i];
            itemSprite.destroy();
        }

        border = me.getBorder();
        if (border) {
            me.borderSprite = border;
        }

        me.updateTheme(chart.getTheme());
    },

    /**
     * @private
     * Updates the given legend item sprite based on store record data.
     * @param {Ext.chart.legend.sprite.Item} sprite
     * @param {Ext.chart.legend.store.Item} record
     */
    updateSprite: function (sprite, record) {
        var data = record.data,
            chart = this.getChart(),
            series = chart.get(data.series),
            marker, label, markerConfig;

        if (sprite) {
            label = sprite.getLabel();
            label.setAttributes({
                text: data.name
            });

            sprite.setAttributes({
                enabled: !data.disabled
            });
            sprite.setConfig({
                series: data.series,
                record: record
            });

            markerConfig = series.getMarkerStyleByIndex(data.index);
            Ext.apply(markerConfig, this.getMarker());
            marker = sprite.getMarker();
            marker.setAttributes({
                fillStyle: markerConfig.fillStyle,
                strokeStyle: markerConfig.strokeStyle
            });
            sprite.layoutUpdater(sprite.attr);
        }
    },

    updateChart: function (newChart, oldChart) {
        var me = this;

        if (oldChart) {
            me.setSurface(null);
        }
        if (newChart) {
            me.setSurface(newChart.getSurface('legend'));
        }
    },

    updateSurface: function (surface, oldSurface) {
        if (oldSurface) {
            oldSurface.el.un('click', 'onClick', this);
        }
        if (surface) {
            surface.isLegendSurface = true;
            surface.el.on('click', 'onClick', this);
        }
    },

    onClick: function (event, surface) {
        var chart = this.getChart(),
            surface = this.getSurface(),
            result, point;

        if (chart && chart.hasFirstLayout && surface) {
            point = surface.getEventXY(event);
            result = surface.hitTest(point);
            if (result && result.sprite) {
                this.toggleItem(result.sprite);
            }
        }
    },

    applyBackground: function (newBackground, oldBackground) {
        var me = this,
            // It's important to get the `chart` first here,
            // because the `surface` is set by the `chart` updater.
            chart = me.getChart(),
            surface = me.getSurface(),
            background;

        background = chart.refreshBackground(surface, newBackground, oldBackground);
        if (background) {
            background.setAttributes({
                zIndex: me.spriteZIndexes.background
            });
        }

        return background;
    },

    resizeBackground: function (surface, background) {
        var width = background.attr.width,
            height = background.attr.height,
            surfaceRect = surface.getRect();

        if (surfaceRect && (width !== surfaceRect[2] || height !== surfaceRect[3])) {
            background.setAttributes({
                width: surfaceRect[2],
                height: surfaceRect[3]
            });
        }
    },

    themeableConfigs: {
        background: true
    },

    updateTheme: function (theme) {
        var me = this,
            surface = me.getSurface(),
            sprites = surface.getItems(),
            legendTheme = theme.getLegend(),
            labelConfig = me.getLabel(),
            configs = me.self.getConfigurator().configs,
            themeableConfigs = me.themeableConfigs,
            initialConfig = me.getInitialConfig(),
            defaultConfig = me.defaultConfig,
            value, cfg, isObjValue, isUnusedConfig, initialValue,
            sprite, style, labelSprite,
            key, attr,
            i, ln;

        for (i = 0, ln = sprites.length; i < ln; i++) {
            sprite = sprites[i];
            if (sprite.isLegendItem) {
                style = legendTheme.label;
                if (style) {
                    attr = null;
                    for (key in style) {
                        if (!(key in labelConfig)) {
                            attr = attr || {};
                            attr[key] = style[key];
                        }
                    }
                    if (attr) {
                        labelSprite = sprite.getLabel();
                        labelSprite.setAttributes(attr);
                    }
                }
                continue;
            } else if (sprite.isLegendBorder) {
                style = legendTheme.border;
            } else {
                continue;
            }
            if (style) {
                attr = {};
                for (key in style) {
                    if (!(key in sprite.config)) {
                        attr[key] = style[key];
                    }
                }
                sprite.setAttributes(attr);
            }
        }

        value = legendTheme.background;
        cfg = configs.background;
        if (value !== null && value !== undefined && cfg) {

        }

        for (key in legendTheme) {
            if (!(key in themeableConfigs)) {
                continue;
            }
            value = legendTheme[key];
            cfg = configs[key];
            if (value !== null && value !== undefined && cfg) {
                initialValue = initialConfig[key];
                isObjValue = Ext.isObject(value);
                isUnusedConfig = initialValue === defaultConfig[key];
                if (isObjValue) {
                    if (isUnusedConfig && themeOnlyIfConfigured[key]) {
                        continue;
                    }
                    value = Ext.merge({}, value, initialValue);
                }
                if (isUnusedConfig || isObjValue) {
                    me[cfg.names.set](value);
                }
            }
        }
    },

    updateStore: function (store, oldStore) {
        var me = this;

        if (oldStore) {
            oldStore.un('datachanged', me.onDataChanged, me);
            oldStore.un('update', me.onDataUpdate, me);
        }
        if (store && !store.isEmptyStore) {
            store.on('datachanged', me.onDataChanged, me);
            store.on('update', me.onDataUpdate, me);
            me.onDataChanged(store);
        }

        me.performLayout();
    },

    onDataChanged: function (store) {
        this.updateSprites();
        this.scheduleLayout();
    },

    onDataUpdate: function (store, record) {
        var me = this,
            sprites = me.sprites,
            ln = sprites.length,
            i = 0,
            sprite, spriteRecord, match;

        for (; i < ln; i++) {
            sprite = sprites[i];
            spriteRecord = sprite.getRecord();
            if (spriteRecord === record) {
                match = sprite;
                break;
            }
        }

        if (match) {
            me.updateSprite(match, record);
            me.scheduleLayout();
        }
    },

    toggleItem: function (sprite) {
        if (!this.getToggleable() || !sprite.isLegendItem) {
            return;
        }
        var store = this.getStore(),
            disabledCount = 0, disabled,
            canToggle = true,
            i, count, record;

        if (store) {
            count = store.getCount();
            for (i = 0; i < count; i++) {
                record = store.getAt(i);
                if (record.get('disabled')) {
                    disabledCount++;
                }
            }
            canToggle = count - disabledCount > 1;

            record = sprite.getRecord();
            if (record) {
                disabled = record.get('disabled');
                if (disabled || canToggle) {
                    // This will trigger AbstractChart.onUpdateLegendStore.
                    record.set('disabled', !disabled);
                    sprite.setAttributes({
                        enabled: disabled
                    });
                }
            }
        }
    },

    destroy: function () {
        this.cancelLayout();
        this.callParent();
    }

});


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ScrollViewSnap : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
    private bool dragging = false, snapped = false;
    public int index = 0;
    public Transform contentTf;
    [SerializeField]
    private Vector3 target;
    [SerializeField]
    private Transform[] kids;
    [SerializeField]
    private float[] distances;
    public Transform middlePoint;

    [SerializeField]
    private Text[] elementLabels;
    public Color textSelectedColor;
    public Color textUnselectedColor = Color.white;
    [SerializeField]
    private int lastIndex = -1;

    public delegate void OnIndexChanged(int index);
    public static event OnIndexChanged onIndexChanged;
    public RectTransform viewport;
    public GameObject aboutpanel;
    public MainController _mainController;

    private void Awake()
    {
        MainUI.Instance.scrollViewSnap = this;
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        dragging = true;
        snapped = false;
        if (aboutpanel.activeSelf) {
            aboutpanel.SetActive(false);
            MainUI.Instance.About_BG_ON();
        }
    }

    public void OnDrag(PointerEventData eventData)
    {

    }

    public void OnEndDrag(PointerEventData eventData)
    {
        dragging = false;
    }
    private void Start()
    {
        if (_mainController == null)
        {
            _mainController = FindObjectOfType<MainController>();
        }
        kids = new Transform[contentTf.transform.childCount];
        distances = new float[kids.Length];
        for (int i = 0; i < kids.Length; i++)
        {
            kids[i] = contentTf.transform.GetChild(i);
        }
        elementLabels = contentTf.GetComponentsInChildren<Text>();
        UpdateLabelsColor();
        StartCoroutine(MoveToButtonOnStart(2));
    }

    public IEnumerator MoveToButtonOnStart(int index)
    {
        yield return new WaitForSeconds(0.1f);
        kids[index].GetComponent<Button>().onClick.Invoke();
    }
    public bool isInvoked = false;
    int prevIndex;
    private void Update()
    {

        for (int i = 0; i < kids.Length; i++)
        {
            distances[i] = Mathf.Abs(Vector3.Distance(middlePoint.position, kids[i].position));
        }

        if (distances.Min() < 80)
        {
            index = Array.IndexOf(distances, distances.Min());

            if (!isInvoked && index != prevIndex)
            {
                isInvoked = true;
                kids[index].GetComponent<Button>().onClick.Invoke();

                prevIndex = index;
                //print(kids[index].name);
            }

        }
        else
        {
            isInvoked = false;
        }

        //if (!dragging && !snapped)
        //{

        //    snapped = true;
        //    for (int i = 0; i < kids.Length; i++)
        //    {
        //        distances[i] = Mathf.Abs(Vector3.Distance(middlePoint.position, kids[i].position));
        //    }
        //    index = Array.IndexOf(distances, distances.Min());
        //    //print(index);

        //    target = Vector3.zero;
        //    kids[index].GetComponent<Button>().onClick.Invoke();
        //}
    }

    public void MoveButton(int index)
    {
        this.index = index;
        target = new Vector3(index * -kids[0].GetComponent<RectTransform>().rect.width, 0, 0);

        if (index != 7)
        {
            if (aboutpanel.activeSelf)
            {
                aboutpanel.SetActive(false);
                MainUI.Instance.About_BG_ON();
            }
        }
        _mainController.ToppleOff();
        onIndexChanged(index);
        UpdateLabelsColor();
        StartCoroutine(MoveToPosition());
    }

    int count = 0;
    public IEnumerator MoveToPosition()
    {
        count++;
        var currentPos = contentTf.localPosition;
        var t = 0f;
        while (t < 1)
        {
            t += Time.deltaTime / 0.3f;
            if (count > 0)
            {
                contentTf.localPosition = Vector3.Lerp(currentPos, target, t);
                float x = Mathf.Abs(Vector3.Distance(middlePoint.position, kids[index].position));
                if (index == 0)
                {
                    contentTf.localPosition += new Vector3(-x + 100, 0f, 0f);
                }
                else if (index == 7)
                {
                    contentTf.localPosition += new Vector3(-x -150, 0f, 0f);
                }
                else
                {
                    contentTf.localPosition += new Vector3(-x - 50, 0f, 0f);
                }

            }
            yield return null;
        }

    }
    private void UpdateLabelsColor()
    {
        if (lastIndex != index)
        {
            foreach (var item in elementLabels)
            {
                item.color = textUnselectedColor;
            }
            elementLabels[index].color = textSelectedColor;
            lastIndex = index;
        }

    }
}


text:
function EventEmitter2() {};

EventEmitter2.prototype.on = function (event, fn) {
  this._callbacks = this._callbacks || {};
  (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
    .push(fn);
  return this;
};

EventEmitter2.prototype.once = function (event, fn) {
  function on() {
    this.off(event, on);
    fn.apply(this, arguments);
  }

  on.fn = fn;
  this.on(event, on);
  return this;
};

EventEmitter2.prototype.off = function (event, fn) {
  this._callbacks = this._callbacks || {};
  var callbacks = this._callbacks['$' + event];

  if (callbacks) {
    if (!fn) this._callbacks['$' + event] = []; // remove all _callbacks of given event
    else {
      var index = callbacks.indexOf(fn);
      if (index >= 0) callbacks.splice(index, 1);
    }
  }

  return this;
};

EventEmitter2.prototype.emit = function(event) {
  this._callbacks = this._callbacks || {};
  var args = [].slice.call(arguments, 1), callbacks = this._callbacks['$' + event];

  if (callbacks) {
    callbacks = callbacks.slice(0);
    for (var i = 0, len = callbacks.length; i < len; ++i) {
      callbacks[i].apply(this, args);
    }
  }

  return this;
};

EventEmitter2.prototype.listeners = function(event){
  this._callbacks = this._callbacks || {};
  return this._callbacks['$' + event] || [];
};

EventEmitter2.prototype.hasListeners = function(event){
  return !!this.listeners(event).length;
};

EventEmitter2.prototype.removeAllListeners = function(event){
  delete this._callbacks['$' + event]
};

EventEmitter2.prototype.removeListener = EventEmitter2.prototype.off

exports.EventEmitter = EventEmitter2;


text:
package cc.protea.crmtext.model;

import cc.protea.util.http.Response;

public class CRMTextException extends RuntimeException {

	private static final long serialVersionUID = 1L;
	public Response response = null;
	public String errorMessage;
	public String errorCode;

	public CRMTextException() {
		super();
	}

	public CRMTextException(final Exception e) {
		super(e);
	}

	public CRMTextException(final Exception e, final Response response) {
		super(e);
		this.response = response;
	}

	public CRMTextException(final Exception e, final String errorCode, final String errorMessage) {
		super(e);
		this.errorCode = errorCode;
		this.errorMessage = errorMessage;
	}
}


text:
import argparse
import io
import re
from collections import defaultdict

NCT_REGEX = re.compile('^[0-9]+\|NCT[0-9]+')

def process(in_file):
    with io.open(in_file, 'r', encoding='utf-8') as fh:
        header = fh.readline().strip().split("|")
        print header

        results = []
        cur = []
        for line in fh:
            mo = re.match(NCT_REGEX, line)
            if mo:
                if cur != []:
                    results.append(cur)
                    cur = []
                cur.append(line.strip())
            else:
                cur.append(line.strip())

        cleaned = defaultdict(list)
        for result in results:
            res = ("").join(result).split("|")
            new_res = dict(zip(header, res))
            cleaned[new_res["NCT_ID"]].append(res)

        results_count = 0

        for k, v in cleaned.items():
            results_count += len(v)

        print "Studies: %s Total results:%s" % (len(cleaned), results_count)
    return None

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-in')

    args = parser.parse_args()

    process(getattr(args, 'in'))


text:
''' <summary>
''' Class encapsulates tokens and secret to create OAuth signatures and return Authorization headers for web requests.
''' </summary>
Public Class OAuthHeader
    Private ReadOnly appSecret As String
    Private ReadOnly accessSecret As String

    Private Const signatureMethod As String = "HMAC-SHA1"
    Private Const version As String = "1.0"

    ''' <summary>All Header params compiled into a Dictionary</summary>
    Private ReadOnly headerParams As IDictionary(Of String, String)

    ''' <summary>
    ''' Constructor
    ''' </summary>
    Public Sub New(appToken As String, appSecret As String, accessToken As String, accessSecret As String)
        Me.appSecret = appSecret
        Me.accessSecret = accessSecret

        ' Initialize all class members
        Me.headerParams = New Dictionary(Of String, String) From {
            {"oauth_consumer_key", appToken},
            {"oauth_token", accessToken},
            {"oauth_nonce", Guid.NewGuid().ToString("n")},
            {"oauth_timestamp", Convert.ToInt32((DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1))).TotalSeconds).ToString()},
            {"oauth_signature_method", signatureMethod},
            {"oauth_version", version}
            }
    End Sub

    ''' <summary>
    ''' Pass request method and URI parameters to get the Authorization header value
    ''' </summary>
    ''' <param name="method">Request Method</param>
    ''' <param name="url">Request URI</param>
    ''' <returns>Authorization header value</returns>
    Public Function getAuthorizationHeader(method As String, url As Uri) As String
        Dim path As String = url.GetLeftPart(UriPartial.Path)

        ' Add the realm parameter to the header params
        Me.headerParams.Add("realm", path)

        'Add query parameter
        Dim query = Web.HttpUtility.ParseQueryString(url.Query)
        For Each p As String In From p1 As String In query Where Not String.IsNullOrWhiteSpace(query.Get(p1))
            Me.headerParams.Add(p, query.Get(p))
        Next

        ' Start composing the base string from the method and request URI
        Dim baseString As String = $"{method.ToUpper}&{Uri.EscapeDataString(path)}&"

        ' Gather, encode, and sort the base string parameters
        Dim encodedParams As New SortedDictionary(Of String, String)
        For Each p As KeyValuePair(Of String, String) In From p1 In Me.headerParams Where Not p1.Key.Equals("realm")
            encodedParams.Add(Uri.EscapeDataString(p.Key), Uri.EscapeDataString(p.Value))
        Next

        ' Expand the base string by the encoded parameter=value pairs
        Dim paramStrings As List(Of String) = (From p In encodedParams Select $"{p.Key}={p.Value}").ToList()
        Dim paramString As String = Uri.EscapeDataString(String.Join(Of String)("&", paramStrings))
        baseString &= paramString

        ' Create the OAuth signature
        Dim signatureKey As String = Uri.EscapeDataString(Me.appSecret) & "&" & Uri.EscapeDataString(Me.accessSecret)
        Dim hasher As Security.Cryptography.HMAC = Security.Cryptography.HMAC.Create()
        hasher.Key = Text.Encoding.UTF8.GetBytes(signatureKey)
        Dim rawSignature As Byte() = hasher.ComputeHash(Text.Encoding.UTF8.GetBytes(baseString))
        Dim oAuthSignature As String = Convert.ToBase64String(rawSignature)

        ' Include the OAuth signature parameter in the header parameters array
        Me.headerParams.Add("oauth_signature", oAuthSignature)

        ' Construct the header string
        Dim headerParamStrings As List(Of String) = (From p In Me.headerParams Select $"{p.Key}=""{p.Value}""").ToList()

        Dim authHeader As String = $"OAuth {String.Join(Of String)(", ", headerParamStrings)}"

        Return authHeader
    End Function
End Class


text:
//
//  FKFlickrPushUnsubscribe.h
//  FlickrKit
//
//  Generated by FKAPIBuilder on 12 Jun, 2013 at 17:19.
//  Copyright (c) 2013 DevedUp Ltd. All rights reserved. http://www.devedup.com
//
//  DO NOT MODIFY THIS FILE - IT IS MACHINE GENERATED

#import "FKFlickrAPIMethod.h"

typedef enum {
	FKFlickrPushUnsubscribeError_RequiredParameterMissing = 1,		 /* One of the required arguments for the method was not provided. */
	FKFlickrPushUnsubscribeError_InvalidParameterValue = 2,		 /* One of the arguments was specified with an illegal value. */
	FKFlickrPushUnsubscribeError_CallbackFailedOrInvalidResponse = 4,		 /* The verification callback failed, or failed to return the expected response to confirm the un-subscription. */
	FKFlickrPushUnsubscribeError_SubscriptionAwaitingVerificationCallbackResponseTryAgainLater = 6,		 /* A subscription with those details exists already, but it is in a pending (non-verified) state. Please wait a bit for the verification callback to complete before attempting to update the subscription. */
	FKFlickrPushUnsubscribeError_SubscriptionNotFound = 7,		 /* No subscription matching the provided details for this user could be found. */
	FKFlickrPushUnsubscribeError_InvalidSignature = 96,		 /* The passed signature was invalid. */
	FKFlickrPushUnsubscribeError_MissingSignature = 97,		 /* The call required signing but no signature was sent. */
	FKFlickrPushUnsubscribeError_LoginFailedOrInvalidAuthToken = 98,		 /* The login details or auth token passed were invalid. */
	FKFlickrPushUnsubscribeError_UserNotLoggedInOrInsufficientPermissions = 99,		 /* The method requires user authentication but the user was not logged in, or the authenticated method call did not have the required permissions. */
	FKFlickrPushUnsubscribeError_InvalidAPIKey = 100,		 /* The API key passed was not valid or has expired. */
	FKFlickrPushUnsubscribeError_ServiceCurrentlyUnavailable = 105,		 /* The requested service is temporarily unavailable. */
	FKFlickrPushUnsubscribeError_FormatXXXNotFound = 111,		 /* The requested response format was not found. */
	FKFlickrPushUnsubscribeError_MethodXXXNotFound = 112,		 /* The requested method was not found. */
	FKFlickrPushUnsubscribeError_InvalidSOAPEnvelope = 114,		 /* The SOAP envelope send in the request could not be parsed. */
	FKFlickrPushUnsubscribeError_InvalidXMLRPCMethodCall = 115,		 /* The XML-RPC request document could not be parsed. */
	FKFlickrPushUnsubscribeError_BadURLFound = 116,		 /* One or more arguments contained a URL that has been used for abuse on Flickr. */

} FKFlickrPushUnsubscribeError;

/*

Why would you want to do this?

(this method is experimental and may change)

*/
@interface FKFlickrPushUnsubscribe : NSObject <FKFlickrAPIMethod>

/* The type of subscription. See flickr.push.getTopics. */
@property (nonatomic, strong) NSString *topic; /* (Required) */

/* The url for the subscription endpoint (must be the same url as was used when creating the subscription). */
@property (nonatomic, strong) NSString *callback; /* (Required) */

/* The verification mode, either 'sync' or 'async'. See the Google PubSubHubbub spec for details. */
@property (nonatomic, strong) NSString *verify; /* (Required) */

/* The verification token to be echoed back to the subscriber during the verification callback, as per the Google PubSubHubbub spec. Limited to 200 bytes. */
@property (nonatomic, strong) NSString *verify_token;

@end


text:
export declare const DATA_FLIP_ID = "data-flip-id";
export declare const DATA_INVERSE_FLIP_ID = "data-inverse-flip-id";
export declare const DATA_FLIP_COMPONENT_ID = "data-flip-component-id";
export declare const DATA_FLIP_CONFIG = "data-flip-config";
export declare const DATA_PORTAL_KEY = "data-portal-key";
export declare const DATA_EXIT_CONTAINER = "data-exit-container";


text:
namespace mc {
namespace util {

class Tokenizer {
public:
    typedef std::vector<std::string> TokenList;
    typedef TokenList::const_iterator const_iterator;
    typedef TokenList::reference reference;
    typedef TokenList::const_reference const_reference;
    typedef TokenList::size_type size_type;

private:
    std::string m_String;
    TokenList m_Tokens;

public:
    Tokenizer(const std::string &str) : m_String(str) { }

    TokenList::size_type tokenize(char delim, TokenList::size_type max = 0) {
        std::stringstream ss(m_String);
        std::string token = "";
        TokenList::size_type cur = 0;

        m_Tokens.clear();

        if (m_String.length() == 0)
            return 0;

        while (true) {
            cur++;
            if (max > 0 && cur >= max) {
                std::getline(ss, token);
                m_Tokens.push_back(token);
                cur++;
                break;
            }

            if (std::getline(ss, token, delim)) {
                m_Tokens.push_back(token);
            } else {
                if (m_String.at(m_String.length() - 1) == delim) {
                    m_Tokens.push_back("");
                    cur++;
                }
                break;
            }
        }
        return cur - 1;
    }

    TokenList::size_type operator()(char delim, TokenList::size_type max = 0) {
        return tokenize(delim, max);
    }

    const_iterator begin() const { return m_Tokens.begin(); }
    const_iterator end() const { return m_Tokens.end(); }
    reference operator[](TokenList::size_type i) { return m_Tokens[i]; }
    const_reference operator[](TokenList::size_type i) const { return m_Tokens[i]; }
    TokenList::size_type size() const { return m_Tokens.size(); }
};

} // ns util
} // ns mc

#endif