text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta property="og:url"                content="https://ballerinalang.org" />
  <meta property="og:type"               content="article" />
  <meta property="og:title"              content="Flexible. Powerful. Beautiful." />
  <meta property="og:description"        content="Ballerina by Example is a hands-on introduction to Ballerina using annotated example programs. Check out the first example or browse the full list below. " />
  <meta property="og:image"              content="http://ballerinalang.org/img/ballerina-fb.jpg" />
    <link rel="shortcut icon" href="https://ballerinalang.org/img/favicon.ico" type="image/x-icon">
  <link rel="icon" href="https://ballerinalang.org/img/favicon.ico" type="image/x-icon">
    <title>Ballerina by Example: Arrays</title>

     <link href="https://b.content.wso2.com/sites/all/bootstrap/css/bootstrap.css?230617" rel="stylesheet">

    <link rel=stylesheet href="site.css">
    <link href="https://fonts.googleapis.com/css?family=Cairo:200,300,400,600,700,900" rel="stylesheet">
    <link rel=stylesheet href="https://b.content.wso2.com/sites/all/ballerina/ballerina-example.css">

import ballerina.io;function main (string[] args) {
    int[] a = [];
    io:println(lengthof a);
    a = [1, 2, 3, 4, 5, 6, 7, 8];
    io:println(lengthof a);
    a[999] = 23;
    io:println(a[999]);
    io:println(lengthof a);
}

Ballerina by Example: Arrays

All arrays are unbounded in length and support 0 based indexing. Arrays may be sparse as well and they will grow to meet whatever size needed based on the index (subject to memory availability of course).

import ballerina.io;

function main (string[] args) {

Here is how you can create an int array of length 0.

    int[] a = [];
    io:println(lengthof a);

Here is how you can create an array with initial values.

    a = [1, 2, 3, 4, 5, 6, 7, 8];
    io:println(lengthof a);

Arrays are unbounded in length. There arrays will grow whatever size needed based on the given index.
Now the length of the following array should be 1000.

    a[999] = 23;
    io:println(a[999]);
    io:println(lengthof a);
}

$ ballerina run arrays.bal
0
8
23
1000

                          Next example: Array of Arrays.

                          by @ballerinalang | feedback | source

                          This site was generated using a tool developed by @mmcgrana, licensed under CC BY / modified from original


text:
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';

@IonicPage()
@Component({
  selector: 'page-subject',
  templateUrl: 'subject.html',
})
export class SubjectPage {

	constructor(public navCtrl: NavController, public navParams: NavParams) {
	}

}

redpajama_set_name: RedPajamaGithub


text:
<Alloy>
	<Collection src="trailsModel" />
	<Window onClose="destroyModel">
		<View class="container">

					<!--Fungerar nu, visar rätt bild. Är beroende av pics mappen dock. -->
			<TableView id="table" dataCollection="trailsModel">
				<TableViewRow class="row" trailNo="{id}" name="{name}" image="{cover_pic}" length="{length}" infoTxt="{infoTxt}" color="{color}" onClick="showTrailDetails">
				<View class="listItem">
					<ImageView class="listImg" image="{cover_img}"/>
					<View id="lblView">
						<Label class="lblListTitle" text="{name}"/> <Label id="lblKm">Km</Label>
						<Label class="lblListKm" text="{length}"/>
					</View>
					</View>
				</TableViewRow>
			</TableView>
		</View>

		 <!-- Navigeringsmenyn med knappar längst ner på sidan som skickar användaren till vald sida -->
			<View id="menuView">
				<Widget id="menuBar" src="menuWidget" name="widget"/>
			</View>

		</Window>
</Alloy>


text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.io

import java.io.{ FileInputStream, InputStream, PrintStream, File => JFile }
import java.net.{ URI, URL }

/** This object provides convenience methods to create an iterable
 *  representation of a source file.
 *
 *  @author  Burak Emir, Paul Phillips
 *  @version 1.0, 19/08/2004
 */
object Source {
  val DefaultBufSize = 2048

  /** Creates a Source from System.in.
   */
  def stdin = fromInputStream(System.in)

  /** Creates a Source from an Iterable.
   *
   *  @param    iterable  the Iterable
   *  @return   the Source
   */
  def fromIterable(iterable: Iterable[Char]): Source = new Source {
    val iter = iterable.iterator
  } withReset(() => fromIterable(iterable))

  /** Creates a Source instance from a single character.
   */
  def fromChar(c: Char): Source = fromIterable(Array(c))

  /** creates Source from array of characters, with empty description.
   */
  def fromChars(chars: Array[Char]): Source = fromIterable(chars)

  /** creates Source from a String, with no description.
   */
  def fromString(s: String): Source = fromIterable(s)

  /** creates Source from file with given name, setting its description to
   *  filename.
   */
  def fromFile(name: String)(implicit codec: Codec): BufferedSource =
    fromFile(new JFile(name))(codec)

  /** creates Source from file with given name, using given encoding, setting
   *  its description to filename.
   */
  def fromFile(name: String, enc: String): BufferedSource =
    fromFile(name)(Codec(enc))

  /** creates Source from file with given file: URI
   */
  def fromFile(uri: URI)(implicit codec: Codec): BufferedSource =
    fromFile(new JFile(uri))(codec)

  /** creates Source from file with given file: URI
   */
  def fromFile(uri: URI, enc: String): BufferedSource =
    fromFile(uri)(Codec(enc))

  /** creates Source from file, using default character encoding, setting its
   *  description to filename.
   */
  def fromFile(file: JFile)(implicit codec: Codec): BufferedSource =
    fromFile(file, Source.DefaultBufSize)(codec)

  /** same as fromFile(file, enc, Source.DefaultBufSize)
   */
  def fromFile(file: JFile, enc: String): BufferedSource =
    fromFile(file)(Codec(enc))

  def fromFile(file: JFile, enc: String, bufferSize: Int): BufferedSource =
    fromFile(file, bufferSize)(Codec(enc))

  /** Creates Source from file, using given character encoding,
   *  setting its description to filename. Input is buffered in a buffer of
   *  size bufferSize.
   */
  def fromFile(file: JFile, bufferSize: Int)(implicit codec: Codec): BufferedSource = {
    val inputStream = new FileInputStream(file)

    createBufferedSource(
      inputStream,
      bufferSize,
      () => fromFile(file, bufferSize)(codec),
      () => inputStream.close()
    )(codec) withDescription ("file:" + file.getAbsolutePath)
  }

  /** Create a Source from array of bytes, decoding
   *  the bytes according to codec.
   *
   *  @param bytes ...
   *  @param enc   ...
   *  @return      the created Source instance.
   */
  def fromBytes(bytes: Array[Byte])(implicit codec: Codec): Source =
    fromString(new String(bytes, codec.name))

  def fromBytes(bytes: Array[Byte], enc: String): Source =
    fromBytes(bytes)(Codec(enc))

  /** Create a Source from array of bytes, assuming
   *  one byte per character (ISO-8859-1 encoding.)
   */
  def fromRawBytes(bytes: Array[Byte]): Source = fromString(new String(bytes, Codec.ISO8859.name))

  /** creates Source from file with given file: URI
   */
  def fromURI(uri: URI)(implicit codec: Codec): BufferedSource = fromFile(new JFile(uri))(codec)

  /** same as fromURL(new URL(s))(Codec(enc))
   */
  def fromURL(s: String, enc: String): BufferedSource =
    fromURL(s)(Codec(enc))

  /** same as fromURL(new URL(s))
   */
  def fromURL(s: String)(implicit codec: Codec): BufferedSource =
    fromURL(new URL(s))(codec)

  /** same as fromInputStream(url.openStream())(Codec(enc))
   */
  def fromURL(url: URL, enc: String): BufferedSource =
    fromURL(url)(Codec(enc))

  /** same as fromInputStream(url.openStream())(codec)
   */
  def fromURL(url: URL)(implicit codec: Codec): BufferedSource =
    fromInputStream(url.openStream())(codec)

  /** Reads data from inputStream with a buffered reader, using the encoding
   *  in implicit parameter codec.
   *
   *  @param  inputStream  the input stream from which to read
   *  @param  bufferSize   buffer size (defaults to Source.DefaultBufSize)
   *  @param  reset        a () => Source which resets the stream (if unset, reset() will throw an Exception)
   *  @param  close        a () => Unit method which closes the stream (if unset, close() will do nothing)
   *  @param  codec        (implicit) a scala.io.Codec specifying behavior (defaults to Codec.default)
   *  @return              the buffered source
   */
  def createBufferedSource(
    inputStream: InputStream,
    bufferSize: Int = DefaultBufSize,
    reset: () => Source = null,
    close: () => Unit = null
  )(implicit codec: Codec): BufferedSource = {
    // workaround for default arguments being unable to refer to other parameters
    val resetFn = if (reset == null) () => createBufferedSource(inputStream, bufferSize, reset, close)(codec) else reset

    new BufferedSource(inputStream, bufferSize)(codec) withReset resetFn withClose close
  }

  def fromInputStream(is: InputStream, enc: String): BufferedSource =
    fromInputStream(is)(Codec(enc))

  def fromInputStream(is: InputStream)(implicit codec: Codec): BufferedSource =
    createBufferedSource(is, reset = () => fromInputStream(is)(codec), close = () => is.close())(codec)
}

/** The class Source implements an iterable representation
 *  of source data.  Calling method reset returns an identical,
 *  resetted source, where possible.
 *
 *  @author  Burak Emir
 *  @version 1.0
 */
abstract class Source extends Iterator[Char] {
  /** the actual iterator */
  protected val iter: Iterator[Char]

  // ------ public values

  /** description of this source, default empty */
  var descr: String = ""

  var nerrors = 0
  var nwarnings = 0

  /** Convenience method, returns given line (not including newline)
   *  from Source.
   *
   *  @param line the line index, first line is 1
   *  @return     the specified line.
   *
   */
  @deprecated("Use a collections method such as getLines().toIndexedSeq for random access.")
  def getLine(line: Int): String = getLines() drop (line - 1) next

  class LineIterator() extends Iterator[String] {
    private[this] val sb = new StringBuilder

    lazy val iter: BufferedIterator[Char] = Source.this.iter.buffered
    def isNewline(ch: Char) = ch == '\r' || ch == '\n'
    def getc() = iter.hasNext && {
      val ch = iter.next
      if (ch == '\n') false
      else if (ch == '\r') {
        if (iter.hasNext && iter.head == '\n')
          iter.next

        false
      }
      else {
        sb append ch
        true
      }
    }
    def hasNext = iter.hasNext
    def next = {
      sb.clear
      while (getc()) { }
      sb.toString
    }
  }

  /** Returns an iterator who returns lines (NOT including newline character(s)).
   *  It will treat any of \r\n, \r, or \n as a line separator (longest match) - if
   *  you need more refined behavior you can subclass Source#LineIterator directly.
   */
  def getLines(): Iterator[String] = new LineIterator()

  /** Returns true if this source has more characters.
   */
  def hasNext = iter.hasNext

  /** Returns next character.
   */
  def next: Char = positioner.next

  class Positioner {
    /** the last character returned by next. */
    var ch: Char = _

    /** position of last character returned by next */
    var pos = 0

    /** current line and column */
    var cline = 1
    var ccol = 1

    /** default col increment for tabs '\t', set to 4 initially */
    var tabinc = 4

    def next: Char = {
      ch = iter.next
      pos = Position.encode(cline, ccol)
      ch match {
        case '\n' =>
          ccol = 1
          cline += 1
        case '\t' =>
          ccol += tabinc
        case _ =>
          ccol += 1
      }
      ch
    }
  }
  object NoPositioner extends Positioner {
    override def next: Char = iter.next
  }
  def ch = positioner.ch
  def pos = positioner.pos

  /** Reports an error message to the output stream out.
   *
   *  @param pos the source position (line/column)
   *  @param msg the error message to report
   *  @param out PrintStream to use (optional: defaults to Console.err)
   */
  def reportError(
    pos: Int,
    msg: String,
    out: PrintStream = Console.err)
  {
    nerrors += 1
    report(pos, msg, out)
  }

  private def spaces(n: Int) = List.fill(n)(' ').mkString
  /**
   *  @param pos the source position (line/column)
   *  @param msg the error message to report
   *  @param out PrintStream to use
   */
  def report(pos: Int, msg: String, out: PrintStream) {
    val line = Position line pos
    val col = Position column pos

    out println "%s:%d:%d: %s%s%s^".format(descr, line, col, msg, getLine(line), spaces(col - 1))
  }

  /**
   *  @param pos the source position (line/column)
   *  @param msg the warning message to report
   *  @param out PrintStream to use (optional: defaults to Console.out)
   */
  def reportWarning(
    pos: Int,
    msg: String,
    out: PrintStream = Console.out)
  {
    nwarnings += 1
    report(pos, "warning! " + msg, out)
  }

  private[this] var resetFunction: () => Source = null
  private[this] var closeFunction: () => Unit = null
  private[this] var positioner: Positioner = new Positioner

  def withReset(f: () => Source): this.type = {
    resetFunction = f
    this
  }
  def withClose(f: () => Unit): this.type = {
    closeFunction = f
    this
  }
  def withDescription(text: String): this.type = {
    descr = text
    this
  }
  // we'd like to default to no positioning, but for now we break
  // less by defaulting to status quo.
  def withPositioning(on: Boolean): this.type = {
    positioner = if (on) new Positioner else NoPositioner
    this
  }

  /** The close() method closes the underlying resource. */
  def close(): Unit     =
    if (closeFunction != null) closeFunction()

  /** The reset() method creates a fresh copy of this Source. */
  def reset(): Source =
    if (resetFunction != null) resetFunction()
    else throw new UnsupportedOperationException("Source's reset() method was not set.")
}


text:
package net.bytebuddy.implementation.bytecode.assign.primitive;

import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.objectweb.asm.MethodVisitor;

import java.util.Arrays;
import java.util.Collection;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;

@RunWith(Parameterized.class)
public class PrimitiveWideningDelegateTrivialTest {

    private final Class<?> sourceType;

    private final Class<?> targetType;

    @Rule
    public MethodRule mockitoRule = MockitoJUnit.rule().silent();

    @Mock
    private TypeDescription sourceTypeDescription, targetTypeDescription;

    @Mock
    private MethodVisitor methodVisitor;

    @Mock
    private Implementation.Context implementationContext;

    public PrimitiveWideningDelegateTrivialTest(Class<?> sourceType, Class<?> targetType) {
        this.sourceType = sourceType;
        this.targetType = targetType;
    }

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {boolean.class, boolean.class},
                {byte.class, byte.class},
                {byte.class, short.class},
                {byte.class, int.class},
                {short.class, short.class},
                {short.class, int.class},
                {char.class, int.class},
                {char.class, char.class},
                {int.class, int.class},
                {long.class, long.class},
                {float.class, float.class},
                {double.class, double.class}
        });
    }

    @Before
    public void setUp() throws Exception {
        when(sourceTypeDescription.represents(sourceType)).thenReturn(true);
        when(targetTypeDescription.represents(targetType)).thenReturn(true);
    }

    @After
    public void tearDown() throws Exception {
        verifyNoMoreInteractions(implementationContext);
        verifyNoMoreInteractions(methodVisitor);
    }

    @Test
    public void testNoOpAssignment() throws Exception {
        StackManipulation stackManipulation = PrimitiveWideningDelegate.forPrimitive(sourceTypeDescription).widenTo(targetTypeDescription);
        assertThat(stackManipulation.isValid(), is(true));
        StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
        assertThat(size.getSizeImpact(), is(0));
        assertThat(size.getMaximalSize(), is(0));
        verify(sourceTypeDescription, atLeast(1)).represents(sourceType);
        verify(targetTypeDescription, atLeast(1)).represents(sourceType);
    }
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-index-projects',
  templateUrl: './index-projects.component.html',
  styleUrls: ['./index-projects.component.scss']
})
export class IndexProjectsComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
"""
``aruco.py``: using the aruco bindings
--------------------------------------

This is a simple example program which takes two command-line arguments: the
input image to load which contains aruco markers and an output image filename
to write a copy of the input image with the detected marker positions drawn
into it.

"""
import logging
logging.basicConfig(level = logging.DEBUG)

import os
import sys
from numpy import array
from PIL import Image

# Where is this file?
this_dir = os.path.abspath(os.path.dirname(__file__))

# Insert a path to load modules from relative to this file
sys.path.insert(0, os.path.abspath(os.path.join(this_dir, '..')))

# Load the aruco module.
from ardrone.aruco import detect_markers

def main():
  """The main entry point of the program."""

  # Check the command-line arcuments.
  if len(sys.argv) < 3:
    print('usage: aruco.py input.png output.png')
    sys.exit(1)

  # This is probably the simplest possible example.
  im = Image.open(sys.argv[1]).convert('RGB')
  arr = array(im)
  [m.draw(arr) for m in detect_markers(im)]
  Image.fromarray(arr).save(sys.argv[2], 'PNG')

if __name__ == '__main__':
  main()


text:
<?php
/**
 * Message translations.
 *
 * This file is automatically generated by 'yii message' command.
 * It contains the localizable messages extracted from source code.
 * You may modify this file by translating the extracted messages.
 *
 * Each array element represents the translation (value) of a message (key).
 * If the value is empty, the message is considered as not translated.
 * Messages that no longer need translation will have their translations
 * enclosed between a pair of '@@' marks.
 *
 * Message string can be used with plural forms format. Check i18n section
 * of the guide for details.
 *
 * NOTE: this file must be saved in UTF-8 encoding.
 */
return [
    'Could not extract module!' => 'Não foi possível extrair módulo!',
    'Download of module failed!' => 'Download do módulo falhou!',
    'Module directory %modulePath% is not writeable!' => 'O diretório do módulo %modulePath% não é gravável!',
    'Module download failed! (%error%)' => 'Módulo de download falhou!  (%error%)',
    'No compatible module version found!' => 'Nenhuma versão compatível  do módulo foi encontrada!',
];


text:
opera.isReady(function() {
    createMenuItem({})

    menu.addItem(m[0])

    test(function() {
      assert_equals(m[0].type, "entry", "The default type should be entry.")
    }, "Default MenuItem type.");

    test(function() {
      assert_true(Array.isArray(m[0].contexts), "The contexts property should be an array.")
      assert_array_equals(m[0].contexts, ["page"], "The default contexts array should contain nothing.")
    }, "Default MenuItem contexts.");

    test(function() {
      assert_equals(m[0].title, "", "The title property should default to an empty string.")
    }, "Default MenuItem title.");

    test(function() {
      assert_false(m[0].disabled, "The disabled property should default to false.")
    }, "Default MenuItem disabled state.");

    test(function() {
      assert_equals(m[0].icon, "", "The icon property should default to an empty string.")
    }, "Default MenuItem icon.");

    test(function() {
      assert_equals(m[0].id, "", "The id property should default to an empty string.")
    }, "Default MenuItem id.");

    test(function() {
      assert_equals(m[0].documentURLPatterns, null, "The documentURLPatterns property should default to an null.")
    }, "Default MenuItem documentURLPatterns.");

    test(function() {
      assert_equals(m[0].targetURLPatterns, null, "The targetURLPatterns property should default to an null.")
    }, "Default MenuItem targetURLPatterns.");

    test(function() {
      assert_equals(m[0].onclick, null, "The onclick property should default to null.")
    }, "Default MenuItem onclick handler");
});


text:
using System.Threading.Tasks;

class Program
{
    static int Main(string[] args) => Run(args).GetAwaiter().GetResult();

    static ValueTask<int> Run(string[] args)
    {
        return new ValueTask<int>(0);
    }
}


text:
package com.laudandjolynn.mytv.crawler.epg;

import com.laudandjolynn.mytv.crawler.Crawler;
import com.laudandjolynn.mytv.crawler.CrawlerFactory;

/**
 * @author: Laud
 * @email: htd0324@gmail.com
 * @date: 2015年4月16日 下午12:27:25
 * @copyright: www.laudandjolynn.com
 */
public class EpgCrawlerFactory implements CrawlerFactory {
	@Override
	public Crawler createCrawler() {
		return new EpgCrawler();
	}
}


text:
"use strict";
import {Item} from "./../item";
import {FoodItem} from "./foodItem";
import {ItemFactory} from "./../../itemFactory";
import * as itemFactoryManager from "./../../../managers/itemFactoryManager";

export class RavelloBeansItem extends FoodItem
{
	constructor()
	{
		super();

		this.hunger = 40;

		this.name = "Ravello Beans";
		this.defaultSlots = [
			[1],
			[1],
		];
	}
}

itemFactoryManager.add(RavelloBeansItem.name, "default", new ItemFactory(() =>
{
	return new RavelloBeansItem();
}));


text:
<resources>
    <string name="app_name">BallViewTest</string>
</resources>


text:
<FindBugsFilter>
    <Match>
        <Class name="com.couchbase.lite.replicator.PullerInternal" />
        <Field name="CHANGE_TRACKER_RESTART_DELAY_MS" />
        <Bug pattern="MS_SHOULD_BE_FINAL" />
    </Match>
</FindBugsFilter>


text:
set -e

function usage() {
  echo "Usage: ./build_and_deploy.sh [vagrant box name]"
  exit
}

if [ $# -ne 1 ]; then
  usage
fi

export SSH_AUTH_SOCK=""
if [ $1 == "windows_7_64" ]; then
  # Check osssigncode is installed and bail early if not.
  echo "Checking for osslsigncode, required to sign windows executables."
  which osslsigncode
  if [ $? -ne 0 ]; then
    echo "Missing osslsigncode, required to sign windows executables."
    exit 1
  fi
  # First, build the templates on windows. See Vagrantfile for info on why we
  # use --provision. These templates don't go into a timestamped directory
  # because the next step runs on linux and needs to know where to find them.
  vagrant reload --provision windows_7_64
  if [ $? -eq 0 ]; then
    vagrant halt $1
  fi
  cd ../../
  PYTHONPATH=. python grr/client/client_build.py --config=grr/config/grr-server.yaml --platform windows --sign buildanddeploy --templatedir grr/executables/windows/templates
  cd -
else
  vagrant up $1
  vagrant ssh -c "cd / && source ~/PYTHON_ENV/bin/activate && PYTHONPATH=. python grr/client/client_build.py --config=grr/config/grr-server.yaml buildanddeploy" $1
  if [ $? -eq 0 ]; then
    vagrant halt $1
  fi
fi


text:
module Spree
  class UserSerializer < BaseSerializer
    attributes *_helper.user_attributes
    attributes :spree_api_key
    has_one :bill_address, key: :bill_address, serializer: AddressSerializer
    has_one :ship_address, key: :ship_address, serializer: AddressSerializer
  end
end


text:
import React from 'react';
import { Input } from 'antd';

const MAX_LENGTH = 15

export default class CoordinateInput extends React.Component {

  handleLocationChange(field, e) {
		if (e.target.value === '-'
      || (field.includes('lat') && this.isLatitude(e.target.value))
			|| (field.includes('long') && this.isLongitude(e.target.value))) {
		 	this.props.onLocationChange(field, e)
		}
  }

	isLatitude(lat) {
  	return isFinite(lat) && Math.abs(lat) <= 90
  }

  isLongitude(lng) {
  	return isFinite(lng) && Math.abs(lng) <= 180
	}

	render() {
		return (
      <div className="isoInputFieldset">
        <Input
        	addonBefore={ this.props.label }
        	value={ this.props.value }
        	maxLength={ MAX_LENGTH }
        	onChange={ this.handleLocationChange.bind(this, this.props.coordinate) }
          disabled={ !this.props.enabled }
        />
      </div>
		)
	}
}


text:
package com.eftimoff.udacitypopmovies.favourites.di;

import com.eftimoff.udacitypopmovies.favourites.FavouritesActivity;
import com.eftimoff.udacitypopmovies.favourites.FavouritesView;
import com.eftimoff.udacitypopmovies.favourites.presenter.FavouritesPresenter;
import com.eftimoff.udacitypopmovies.favourites.presenter.FavouritesPresenterImpl;
import com.eftimoff.udacitypopmovies.popmovies.posters.adapter.PostersAdapter;

import dagger.Module;
import dagger.Provides;

@Module
public class FavouritesModule {

    private FavouritesActivity favouritesActivity;

    public FavouritesModule(FavouritesActivity favouritesActivity) {
        this.favouritesActivity = favouritesActivity;
    }

    @Provides
    PostersAdapter providePostersAdapter() {
        return new PostersAdapter(null);
    }

    @Provides
    FavouritesView provideFavouritesView() {
        return favouritesActivity;
    }

    @Provides
    FavouritesPresenter provideFavouritesPresenter(final FavouritesPresenterImpl favouritesPresenter) {
        return favouritesPresenter;
    }

}


text:
package com.android.tools.idea.tests.gui.framework.fixture;

import com.intellij.execution.junit2.ui.model.JUnitRunningModel;
import com.intellij.execution.testframework.TestTreeView;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Fixture for the tree widget, on the left hand side of "Run" window (when running tests).
 */
public class UnitTestTreeFixture {
  private ExecutionToolWindowFixture.ContentFixture myContentFixture;
  private final TestTreeView myTreeView;

  public UnitTestTreeFixture(@NotNull ExecutionToolWindowFixture.ContentFixture contentFixture,
                             @NotNull TestTreeView treeView) {
    myContentFixture = contentFixture;
    myTreeView = treeView;
  }

  @Nullable
  public JUnitRunningModel getModel() {
    return (JUnitRunningModel)myTreeView.getData(TestTreeView.MODEL_DATA_KEY.getName());
  }

  public boolean isAllTestsPassed() {
    return !getModel().getProgress().hasDefects();
  }

  public int getFailingTestsCount() {
    return getModel().getProgress().countDefects();
  }

  @NotNull
  public ExecutionToolWindowFixture.ContentFixture getContent() {
    return myContentFixture;
  }
}


text:
[![](https://github.com/fiji/OMEVisual/actions/workflows/build-main.yml/badge.svg)](https://github.com/fiji/OMEVisual/actions/workflows/build-main.yml)

# OMEVisual

`OMEVisual` is a Fiji plugin to easily visualize OME metadata.

See also the Wiki page : http://imagej.net/OMEVisual

Please note that :

- This goal of this plugin is **not to implement** all the OME features.
- This plugin makes several strong assumptions about the OME model in order to simplify the interface :
    - Each image contains only one `Pixels` element.
    - Each `TiffData` contains only one `Plane`.
    - `Plane` and `TiffData` informations are displayed at the same location without distinction.
- Any ideas to improve the visualization and/or add OME features is very welcome :
    - The best way is to submit a PR.
    - You can also open an issue and post an OME-TIFF file which contains additional OME features you would like to see added to the plugin.

The plugin has been tested on the following OME sample dataset http://downloads.openmicroscopy.org/images/OME-TIFF/2015-01/bioformats-artificial/multi-channel-4D-series.ome.tif and with an OME TIFF file generated by Micro-Manager.

## How to use

- Open your image in Fiji.
- Start the plugin with `Plugins ► Utilities ► Visualize OME Metadata`.
- A window should open with the metadata in it.

![OMEVisual Screenshot](screenshot.png)

## Authors

`OMEVisual` has been created by [Hadrien Mary](mailto:hadrien.mary@gmail.com).

This work started in 2016 at the [Gary Brouhard laboratory](http://brouhardlab.mcgill.ca/) at the University of McGill.

## License

MIT. See [LICENSE.txt](LICENSE.txt)


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gbif.registry.ws.advice;

import java.util.Optional;

import javax.validation.constraints.NotNull;

import org.springframework.core.MethodParameter;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * A class that exists to overwrite 401 response codes with a 403 if the client instructs it to by
 * using the header gbif-prefer-403-over-401=true. This exists because ajax based clients (e.g.
 * Angular, JQuery etc) do not get the response before the browser pops up the Authentication
 * window, which happens on a 401 response. This is a known limitation and this is relatively common
 * practice.
 */
@ControllerAdvice
public class AuthResponseCodeOverwriteFilter implements ResponseBodyAdvice<Object> {

  private static final String REQUEST_HEADER_OVERWRITE = "gbif-prefer-403-over-401";

  @Override
  public boolean supports(
      @NotNull MethodParameter returnType,
      @NotNull Class<? extends HttpMessageConverter<?>> converterType) {
    return true;
  }

  @Override
  public Object beforeBodyWrite(
      Object body,
      @NotNull MethodParameter returnType,
      @NotNull MediaType selectedContentType,
      @NotNull Class<? extends HttpMessageConverter<?>> selectedConverterType,
      @NotNull ServerHttpRequest request,
      @NotNull ServerHttpResponse response) {
    String header =
        Optional.of(request.getHeaders())
            .map(httpHeaders -> httpHeaders.get(REQUEST_HEADER_OVERWRITE))
            .map(requestHeaderOverwrite -> requestHeaderOverwrite.get(0))
            .orElse(null);

    int responseStatusCode =
        ((ServletServerHttpResponse) response).getServletResponse().getStatus();

    if (Boolean.parseBoolean(header) && responseStatusCode == HttpStatus.UNAUTHORIZED.value()) {
      response.setStatusCode(HttpStatus.FORBIDDEN);
    }

    return body;
  }
}


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

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:sec="http://www.springframework.org/schema/security"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    				    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                        http://www.springframework.org/schema/security
                        http://www.springframework.org/schema/security/spring-security-3.0.xsd">

	<sec:http auto-config="true" use-expressions="true">

		<sec:logout logout-success-url="/pages/pg_login.xhtml" invalidate-session="true"/>

		<sec:intercept-url pattern="/pages/pg_login.xhtml"	filters="none" />
		<sec:intercept-url pattern="/css/**"				filters="none" />
		<sec:intercept-url pattern="/images/**"				filters="none" />
		<sec:intercept-url pattern="/js/**"					filters="none" />
		<sec:intercept-url pattern="/rest/**"				filters="none" />
		<sec:intercept-url pattern="/pages/**"				access="isAuthenticated()" />

		<sec:session-management invalid-session-url="/pages/pg_login.xhtml">
			<sec:concurrency-control max-sessions="100" expired-url="/pages/pg_login.xhtml" error-if-maximum-exceeded="false" session-registry-ref="sessionRegistry" />
		</sec:session-management>

		<sec:form-login
			login-page="/pages/pg_login.xhtml"
			login-processing-url="/j_spring_security_check"
			authentication-failure-url="/pages/pg_login.xhtml"
			authentication-success-handler-ref="authSuccessHandler"
			authentication-failure-handler-ref="authErrorHandler" />

	</sec:http>

    <bean id="sessionRegistry" class="org.springframework.security.core.session.SessionRegistryImpl" />

    <sec:authentication-manager alias="authenticationManager">
		<sec:authentication-provider  ref="authenticationProvider" />
	</sec:authentication-manager>

	<bean id="authenticationProvider"
		class="com.alcedomoreno.sirme.web.aut.BSAuthenticationProvider"
		p:userDetailsService-ref="userService"
		p:passwordEncoder-ref="passwordEncoder">
	</bean>

	<bean id="userService"				class="com.alcedomoreno.sirme.web.aut.UserDetailsService"/>
	<bean id="passwordEncoder"			class="org.springframework.security.authentication.encoding.Md5PasswordEncoder" />
	<bean id="authSuccessHandler" 		class="com.alcedomoreno.sirme.web.aut.BSUserAuthenticationSuccessHandler"	p:defaultTargetUrl="/pages/pg_general.xhtml" />
	<bean id="authErrorHandler" 		class="com.alcedomoreno.sirme.web.aut.BSUserAuthenticationErrorHandler"		p:defaultTargetUrl="/pages/pg_login.xhtml" />

</beans>


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>at.irian.ankor.monitor.stats Class Hierarchy (Ankor - Project 0.4-SNAPSHOT API)</title>
<meta name="date" content="2014-09-25">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package at.irian.ankor.monitor.stats

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

at.irian.ankor.monitor.stats.AnkorSystemStats

at.irian.ankor.monitor.stats.ModelSessionStats

at.irian.ankor.monitor.stats.StatsAnkorSystemMonitor (implements at.irian.ankor.monitor.AnkorSystemMonitor)

at.irian.ankor.monitor.stats.StatsModelSessionMonitor (implements at.irian.ankor.monitor.ModelSessionMonitor)

at.irian.ankor.monitor.stats.StatsSwitchboardMonitor (implements at.irian.ankor.monitor.SwitchboardMonitor)

at.irian.ankor.monitor.stats.SwitchboardStats

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014 Ankor Developers Team. All rights reserved.


text:
/**
 * Created by Wayuki on 26-Mar-17.
 */
import toastr from 'toastr';
import { routerActions } from 'react-router-redux';

import * as helpers from '../../../helpers';
import * as authActions from './authActions';

export const handleLogin = success => (
  (dispatch) => {
    if (success) {
      const token = helpers.getCookieData('feathers-jwt');
      dispatch(authActions.authenticate(token)).then(() => {
        toastr.success('You are authenticated.');
        const redirect = window.localStorage.getItem('redirect');
        if (redirect) {
          window.localStorage.removeItem('redirect');
          dispatch(routerActions.replace(redirect));
        } else {
          if (!window.localStorage.getItem('redirected') || window.localStorage.getItem('redirected') !== 'true') { // eslint-disable-line no-lonely-if
            dispatch(routerActions.replace('/'));
          } else {
            window.localStorage.removeItem('redirected');
          }
        }
      }).catch(() => {
        toastr.error('Errors occurred when authenticating. Please try again.');
      });
    } else {
      toastr.error('Errors occurred when authenticating. Please try again.');
    }
  }
);

export default () => {};


text:
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2000-2013 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#ifndef OCTREESCENEMANAGER_H
#define OCTREESCENEMANAGER_H

#include "OgreOctreePrerequisites.h"
#include "OgreSceneManager.h"
#include "OgreRenderOperation.h"
#include "OgreSphere.h"

#include <list>
#include <algorithm>

#include "OgreOctree.h"

namespace Ogre
{

class OctreeNode;

class OctreeCamera;
class OctreeIntersectionSceneQuery;
class OctreeRaySceneQuery;
class OctreeSphereSceneQuery;
class OctreeAxisAlignedBoxSceneQuery;
class OctreePlaneBoundedVolumeListSceneQuery;

typedef list< WireBoundingBox * >::type BoxList;
typedef list< unsigned long >::type ColorList;

/** Specialized SceneManager that divides the geometry into an octree in order to facilitate spatial queries.
*/

class _OgreOctreePluginExport OctreeSceneManager : public SceneManager
{
    friend class OctreeIntersectionSceneQuery;
    friend class OctreeRaySceneQuery;
    friend class OctreeSphereSceneQuery;
    friend class OctreeAxisAlignedBoxSceneQuery;
    friend class OctreePlaneBoundedVolumeListSceneQuery;

public:
    static int intersect_call;
    /** Standard Constructor.  Initializes the octree to -10000,-10000,-10000 to 10000,10000,10000 with a depth of 8. */
    OctreeSceneManager(const String& name);
    /** Standard Constructor */
    OctreeSceneManager(const String& name, AxisAlignedBox &box, int max_depth );
    /** Standard destructor */
    ~OctreeSceneManager();

	/// @copydoc SceneManager::getTypeName
	const String& getTypeName(void) const;

    /** Initializes the manager to the given box and depth.
    */
    void init( AxisAlignedBox &box, int d );

    /** Creates a specialized OctreeNode */
    virtual SceneNode * createSceneNodeImpl ( void );
    /** Creates a specialized OctreeNode */
    virtual SceneNode * createSceneNodeImpl ( const String &name );
    /** Creates a specialized OctreeCamera */
    virtual Camera * createCamera( const String &name );

    /** Deletes a scene node */
    virtual void destroySceneNode( const String &name );

    /** Does nothing more */
    virtual void _updateSceneGraph( Camera * cam );
    /** Recurses through the octree determining which nodes are visible. */
    virtual void _findVisibleObjects ( Camera * cam,
		VisibleObjectsBoundsInfo* visibleBounds, bool onlyShadowCasters );

    /** Alerts each unculled object, notifying it that it will be drawn.
     * Useful for doing calculations only on nodes that will be drawn, prior
     * to drawing them...
     */
    virtual void _alertVisibleObjects( void );

    /** Walks through the octree, adding any visible objects to the render queue.
    @remarks
    If any octant in the octree if completely within the view frustum,
    all subchildren are automatically added with no visibility tests.
    */
    void walkOctree( OctreeCamera *, RenderQueue *, Octree *,
		VisibleObjectsBoundsInfo* visibleBounds, bool foundvisible,
		bool onlyShadowCasters);

    /** Checks the given OctreeNode, and determines if it needs to be moved
    * to a different octant.
    */
    void _updateOctreeNode( OctreeNode * );
    /** Removes the given octree node */
    void _removeOctreeNode( OctreeNode * );
    /** Adds the Octree Node, starting at the given octree, and recursing at max to the specified depth.
    */
    void _addOctreeNode( OctreeNode *, Octree *octree, int depth = 0 );

    /** Recurses the octree, adding any nodes intersecting with the box into the given list.
    It ignores the exclude scene node.
    */
    void findNodesIn( const AxisAlignedBox &box, list< SceneNode * >::type &list, SceneNode *exclude = 0 );

    /** Recurses the octree, adding any nodes intersecting with the sphere into the given list.
    It ignores the exclude scene node.
    */
    void findNodesIn( const Sphere &sphere, list< SceneNode * >::type &list, SceneNode *exclude = 0 );

    /** Recurses the octree, adding any nodes intersecting with the volume into the given list.
      It ignores the exclude scene node.
      */
    void findNodesIn( const PlaneBoundedVolume &volume, list< SceneNode * >::type &list, SceneNode *exclude=0 );

    /** Recurses the octree, adding any nodes intersecting with the ray into the given list.
      It ignores the exclude scene node.
      */
    void findNodesIn( const Ray &ray, list< SceneNode * >::type &list, SceneNode *exclude=0 );

    /** Sets the box visibility flag */
    void setShowBoxes( bool b )
    {
        mShowBoxes = b;
    };

    void setLooseOctree( bool b )
    {
        mLoose = b;
    };

    /** Resizes the octree to the given size */
    void resize( const AxisAlignedBox &box );

    /** Sets the given option for the SceneManager
               @remarks
        Options are:
        "Size", AxisAlignedBox *;
        "Depth", int *;
        "ShowOctree", bool *;
    */

    virtual bool setOption( const String &, const void * );
    /** Gets the given option for the Scene Manager.
        @remarks
        See setOption
    */
    virtual bool getOption( const String &, void * );

    bool getOptionValues( const String & key, StringVector &refValueList );
    bool getOptionKeys( StringVector &refKeys );
    /** Overridden from SceneManager */
    void clearScene(void);

    AxisAlignedBoxSceneQuery* createAABBQuery(const AxisAlignedBox& box, uint32 mask);
    SphereSceneQuery* createSphereQuery(const Sphere& sphere, uint32 mask);
    PlaneBoundedVolumeListSceneQuery* createPlaneBoundedVolumeQuery(const PlaneBoundedVolumeList& volumes, uint32 mask);
    RaySceneQuery* createRayQuery(const Ray& ray, uint32 mask);
    IntersectionSceneQuery* createIntersectionQuery(uint32 mask);

protected:

	Octree::NodeList mVisible;

    /// The root octree
    Octree *mOctree;

    /// List of boxes to be rendered
    BoxList mBoxes;

    /// Number of rendered objs
    int mNumObjects;

    /// Max depth for the tree
    int mMaxDepth;
    /// Size of the octree
    AxisAlignedBox mBox;

    /// Boxes visibility flag
    bool mShowBoxes;

    bool mLoose;

    Real mCorners[ 24 ];
    static unsigned long mColors[ 8 ];
    static unsigned short mIndexes[ 24 ];

    Matrix4 mScaleFactor;

};

/// Factory for OctreeSceneManager
class OctreeSceneManagerFactory : public SceneManagerFactory
{
protected:
	void initMetaData(void) const;
public:
	OctreeSceneManagerFactory() {}
	~OctreeSceneManagerFactory() {}
	/// Factory type name
	static const String FACTORY_TYPE_NAME;
	SceneManager* createInstance(const String& instanceName);
	void destroyInstance(SceneManager* instance);
};

}

#endif


text:
<!DOCTYPE HTML>

  <title>CSS Test: Test of margin-*: calc()</title>
  <link rel="author" title="L. David Baron" href="https://dbaron.org/">
  <link rel="help" href="http://www.w3.org/TR/css3-values/#calc-notation">
  <link rel="match" href="calc-margin-block-1-ref.html">

paragraph with margin

paragraph with margin

paragraph with margin

paragraph with margin

paragraph with margin


text:
package org.strangeforest.tcb.stats.model.records.details;

import com.fasterxml.jackson.annotation.*;

public class SeasonWinningPctRecordDetail extends SeasonWonLostRecordDetail {

	public SeasonWinningPctRecordDetail(
		@JsonProperty("won") int won,
		@JsonProperty("lost") int lost,
		@JsonProperty("season") int season
	) {
		super(won, lost, season);
	}

	@Override public String getValue() {
		return wonLost.getWonPctStr(2);
	}
}


text:
from flask import (
    Blueprint, jsonify, request, current_app, url_for, g, redirect,
    session, abort
)
import sqlite3
from urllib.parse import urljoin
from werkzeug.security import generate_password_hash

api = Blueprint('api', __name__)

@api.route('/')
def index():
    return jsonify(
        users=urljoin(request.host_url, url_for('.users')),
        records=urljoin(request.host_url, url_for('.records'))
    )

@api.route('/users', methods=['GET', 'POST'])
def users():
    if request.method == 'POST':
        try:
            g.db.execute(
                'insert into users (name, password_hash) values (?, ?)',
                [request.json['name'], generate_password_hash(request.json['password'])]
            )
            g.db.commit()
        except sqlite3.IntegrityError:
            return jsonify({"status": "failed"})

        cur = g.db.execute('select id, name from users where name == ?',
                           [request.json['name']])
        user = cur.fetchall()[0]
        return jsonify({
            "id": user[0],
            "name": user[1]
        })

    # GET Request
    cur = g.db.execute('select id, name from users order by id desc')
    users_dict = [dict(id=row[0], name=row[1]) for row in cur.fetchall()]
    return jsonify(users=users_dict)

@api.route('/records')
def records():
    return jsonify(Records=[0, 1, 2])


text:
require 'erb'
require 'etc'
require 'forwardable'
require 'optparse'
require 'pathname'
require 'yaml'

require 'net/ssh'
require 'net/sftp'

# task actions
require 'producer/core/action'
require 'producer/core/actions/echo'
require 'producer/core/actions/shell_command'
require 'producer/core/actions/mkdir'
require 'producer/core/actions/file_append'
require 'producer/core/actions/file_replace_content'
require 'producer/core/actions/file_writer'
require 'producer/core/actions/yaml_writer'

# condition tests
require 'producer/core/test'
require 'producer/core/tests/condition_test'
require 'producer/core/tests/file_contains'
require 'producer/core/tests/file_eq'
require 'producer/core/tests/file_match'
require 'producer/core/tests/has_dir'
require 'producer/core/tests/has_env'
require 'producer/core/tests/has_executable'
require 'producer/core/tests/has_file'
require 'producer/core/tests/shell_command_status'
require 'producer/core/tests/yaml_eq'

require 'producer/core/errors'

require 'producer/core/cli'
require 'producer/core/condition'
require 'producer/core/env'
require 'producer/core/error_formatter'
require 'producer/core/logger_formatter'
require 'producer/core/prompter'
require 'producer/core/recipe'
require 'producer/core/recipe/file_evaluator'
require 'producer/core/remote'
require 'producer/core/remote/environment'
require 'producer/core/remote/fs'
require 'producer/core/task'
require 'producer/core/template/erb_renderer'
require 'producer/core/template/raw_renderer'
require 'producer/core/template/yaml_renderer'
require 'producer/core/template'
require 'producer/core/version'
require 'producer/core/worker'


text:
import * as Knex from "knex";

exports.up = function (knex: Knex): Promise<any> {
  return Promise.all([
    knex.schema.createTable('project', table => {
      table.increments().primary();
      table.integer('owner').references('id').inTable('user').onDelete("CASCADE").onUpdate("CASCADE");
      table.string('name', 64);
    })
  ]);
};

exports.down = function (knex: Knex): Promise<any> {
  return Promise.all([
    knex.schema.dropTable('project')
  ]);
};


text:
AFRAME.registerComponent('arjs-portal-door', {
	schema: {
		url : {		// Url of the content - may be video or image
			type: 'string',
		},
		doorWidth : {	// width of the door
			type: 'number',
			default: 1,
		},
		doorHeight : {	// height of the door
			type: 'number',
			default: 2,
		},
	},
	init: function () {
		var _this = this

		var doorWidth = this.data.doorWidth
		var doorHeight = this.data.doorHeight
		var imageURL = this.data.url

		var portalDoor = new THREEx.Portal360(imageURL, doorWidth, doorHeight)
		this._portalDoor = portalDoor

		this.el.object3D.add(portalDoor.object3d)
	},
	tick: function(){
		this._portalDoor.update()
	}
})

AFRAME.registerPrimitive('a-portal-door', AFRAME.utils.extendDeep({}, AFRAME.primitives.getMeshMixin(), {
	defaultComponents: {
		'arjs-portal-door': {},
	},
	mappings: {
		'url': 'arjs-portal-door.url',
	}
}))


text:
<?php

namespace common\models\bmodels;

use Yii;

/**
 * This is the model class for table "{{%achievement}}".
 *
 * @property integer $id
 * @property string $name
 * @property integer $yearEvaluationID
 * @property string $created_time
 * @property string $updated_time
 */
class BaseAchievement extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%achievement}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'yearEvaluationID', 'created_time', 'updated_time'], 'required'],
            [['yearEvaluationID'], 'integer'],
            [['created_time', 'updated_time'], 'safe'],
            [['name'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'yearEvaluationID' => 'Year Evaluation ID',
            'created_time' => 'Created Time',
            'updated_time' => 'Updated Time',
        ];
    }
}


text:
#pragma once
//#include "../DataOutput.hpp"
#include <geode/DataOutput.hpp>
#include "../IPdxSerializable.hpp"
using namespace System;

namespace Apache
{
  namespace Geode
  {
    namespace Client
    {

				ref class DataOutput;
      ref class DataInput;
      namespace Internal
      {
        ref class PdxType;
        public ref class PdxHelper
        {
        public:

          static void SerializePdx(DataOutput^ dataOutput, IPdxSerializable^ pdxObject);

          static IPdxSerializable^ DeserializePdx(DataInput^ dataOutput, bool forceDeserialize);

          static IPdxSerializable^ PdxHelper::DeserializePdx(DataInput^ dataInput, bool forceDeserialize, int typeId, int length );

          literal Byte PdxHeader = 8;

          static Int32 ReadInt32(System::Byte* offsetPosition);

          static Int32 ReadInt16(System::Byte* offsetPosition);

					static Int32 PdxHelper::ReadUInt16(System::Byte* offsetPosition);

          static Int32 ReadByte(System::Byte* offsetPosition);

          static void WriteInt32(System::Byte* offsetPosition, Int32 value);

          static void WriteInt16(System::Byte* offsetPosition, Int32 value);

          static void WriteByte(System::Byte* offsetPosition, Int32 value);

          static Int32 ReadInt(System::Byte* offsetPosition, int size);

          static Int32 GetEnumValue(String^ enumClassName, String^ enumName, int hashcode);

          static Object^ GetEnum(int enumId);

        private:
          static void CreateMergedType(PdxType^ localType, PdxType^ remoteType, DataInput^ dataInput);
        };
    }  // namespace Client
  }  // namespace Geode
}  // namespace Apache

}


text:
package at.fundev.cis;

public class NetworkLoggerService {

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_shortAnimTime">
    <item android:drawable="@mipmap/ic_tv_control_circle_up_sel" android:state_checked="true"/>
    <item android:drawable="@mipmap/ic_tv_control_circle_up_sel" android:state_selected="true"/>
    <item android:drawable="@mipmap/ic_tv_control_circle_up_sel" android:state_activated="true"/>
    <item android:drawable="@mipmap/ic_tv_control_circle_up_sel" android:state_pressed="true"/>
    <item android:drawable="@mipmap/ic_tv_control_circle_up_nor"/>

</selector>


text:
namespace Medallion.Threading.Internal;

/// <summary>
/// A type which can only store a valid timeout value
/// </summary>
#if DEBUG
public
#else
internal
#endif
readonly struct TimeoutValue : IEquatable<TimeoutValue>, IComparable<TimeoutValue>
{
    public TimeoutValue(TimeSpan? timeout, string paramName = "timeout")
    {
        if (timeout is { } timeoutValue)
        {
            // based on Task.Wait(TimeSpan)
            // https://referencesource.microsoft.com/#mscorlib/system/threading/Tasks/Task.cs,855657030ba22f78

            var totalMilliseconds = (long)timeoutValue.TotalMilliseconds;
            if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
            {
                throw new ArgumentOutOfRangeException(
                    paramName: paramName,
                    actualValue: timeoutValue,
                    message: $"Must be {nameof(Timeout)}.{nameof(Timeout.InfiniteTimeSpan)} ({Timeout.InfiniteTimeSpan}) or a non-negative value <= {TimeSpan.FromMilliseconds(int.MaxValue)})"
                );
            }

            this.InMilliseconds = (int)totalMilliseconds;
        }
        else
        {
            this.InMilliseconds = Timeout.Infinite;
        }
    }

    public int InMilliseconds { get; }
    public int InSeconds => this.IsInfinite ? throw new InvalidOperationException("infinite timeout cannot be converted to seconds") : this.InMilliseconds / 1000;
    public bool IsInfinite => this.InMilliseconds == Timeout.Infinite;
    public bool IsZero => this.InMilliseconds == 0;
    public TimeSpan TimeSpan => TimeSpan.FromMilliseconds(this.InMilliseconds);

    public bool Equals(TimeoutValue that) => this.InMilliseconds == that.InMilliseconds;
    public override bool Equals(object? obj) => obj is TimeoutValue that && this.Equals(that);
    public override int GetHashCode() => this.InMilliseconds;

    public int CompareTo(TimeoutValue that) =>
        this.IsInfinite ? (that.IsInfinite ? 0 : 1)
            : that.IsInfinite ? -1
            : this.InMilliseconds.CompareTo(that.InMilliseconds);

    public static bool operator ==(TimeoutValue a, TimeoutValue b) => a.Equals(b);
    public static bool operator !=(TimeoutValue a, TimeoutValue b) => !(a == b);

    public static implicit operator TimeoutValue(TimeSpan? timeout) => new TimeoutValue(timeout);

    public override string ToString() =>
        this.IsInfinite ? "∞"
            : this.IsZero ? "0"
            : this.TimeSpan.ToString();
}


text:
package com.kasije.core.impl.page;

import com.kasije.core.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.bridje.ioc.Component;
import org.bridje.ioc.InjectNext;
import org.bridje.ioc.Priority;

/**
 *
 */
@Component
@Priority(Integer.MIN_VALUE + 200)
class WebPageHandler implements RequestHandler
{
    @InjectNext
    private RequestHandler handler;

    @Override
    public boolean handle(RequestContext reqCtx) throws IOException
    {
        if(null == handler)
        {
            return false;
        }

        /* was it handled */
        WebPage webPage = reqCtx.get(WebPage.class);
        if (null == webPage)
        {
            WebSite site = reqCtx.get(WebSite.class);
            if(null != site)
            {
                String pageName = findPageName(reqCtx);
                /* find the page using the router */
                webPage = site.findPage(pageName);
                if (null != webPage)
                {
                    reqCtx.put(WebPage.class, webPage);
                }
            }
        }

        return handler.handle(reqCtx);
    }

    private String findPageName(RequestContext reqCtx)
    {
        WebPageRef ref = reqCtx.get(WebPageRef.class);
        if(ref != null)
        {
            return ref.getPage();
        }
        else
        {
            HttpServletRequest req = reqCtx.get(HttpServletRequest.class);
            return req.getPathInfo();
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="css/foundation.css" />
    <link rel="stylesheet" href="css/app.css" />

Nutrition Calculator

Now loading...


text:
require 'spec_helper'

describe Wyatt::Core::Configuration do

  let(:file_path) { "/path/to/file.yml" }

  describe '.load!' do

    let(:core_settings) { 'hello' }
    let(:settings)      { { Wyatt::Core::Configuration::CORE_SETTINGS => core_settings } }

    it 'should initialize the value of file_path' do
      Wyatt::Core::Configuration.stub(:read_yaml) { settings }
      Wyatt::Core::Configuration.load!(file_path)

      Wyatt::Core::Configuration.file_path.should eq(file_path)
    end

    it 'should call read_yaml' do
      Wyatt::Core::Configuration.should_receive(:read_yaml).once.and_return(settings)
      Wyatt::Core::Configuration.load!(file_path)
    end

    it 'should initialize core_settings with the value of the core key' do
      Wyatt::Core::Configuration.stub(:read_yaml) { settings }
      Wyatt::Core::Configuration.load!(file_path)

      Wyatt::Core::Configuration.core_settings.should eq(core_settings)
    end

  end

  describe '.read_yaml' do

    let(:raw_yaml_string) { "this is totally valid yaml" }

    before do
      Wyatt::Core::Configuration.stub(:file_path) { file_path }
    end

    it 'should call IO.read with the file path' do
      YAML.stub!(:load)

      IO.should_receive(:read).once.with(file_path)
      Wyatt::Core::Configuration.read_yaml
    end

    it 'should call YAML::load with the results of IO.read' do
      IO.stub!(:read) { raw_yaml_string }

      YAML.should_receive(:load).once.with(raw_yaml_string)
      Wyatt::Core::Configuration.read_yaml
    end

  end

end


text:
#ifndef ELEKTRA_PLUGIN_BLOCKRESOLVER_H
#define ELEKTRA_PLUGIN_BLOCKRESOLVER_H

#include <kdbplugin.h>

int elektraBlockresolverClose (Plugin * handle, Key * errorKey);
int elektraBlockresolverGet (Plugin * handle, KeySet * ks, Key * parentKey);
int elektraBlockresolverSet (Plugin * handle, KeySet * ks, Key * parentKey);
int elektraBlockresolverError (Plugin * handle, KeySet * ks, Key * parentKey);
int elektraBlockresolverCommit (Plugin * handle, KeySet * ks, Key * parentKey);

Plugin * ELEKTRA_PLUGIN_EXPORT;

#endif


text:
#include <cstdio>

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/type_traits/is_same.hpp>

#include <pr_bgl/partition_all.h>

#include <gtest/gtest.h>

// single vertex
TEST(PartitionAllTestCase, SingleVertexTest)
{
   typedef boost::adjacency_list<
      boost::vecS, // Edgelist ds, for per-vertex out-edges
      boost::vecS, // VertexList ds, for vertex set
      boost::undirectedS // type of graph
      > Graph;
   typedef boost::graph_traits<Graph> GraphTypes;
   typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
   typedef boost::graph_traits<Graph>::vertex_iterator VertexIter;
   typedef boost::graph_traits<Graph>::edge_descriptor Edge;
   typedef boost::graph_traits<Graph>::edge_iterator EdgeIter;
   typedef boost::graph_traits<Graph>::out_edge_iterator EdgeOutIter;
   typedef boost::graph_traits<Graph>::in_edge_iterator EdgeInIter;

   printf("starting test 1 (single vertex):\n");

   Graph g;

   Vertex v = boost::add_vertex(g);

   std::map<Edge,double> weights;

   std::map<std::pair<Vertex,Vertex>, double> coupling_map;

   std::map<Vertex, double> cs_xs;
   std::map<Vertex, double> cs_ty;

   pr_bgl::partition_all(g, 1.0,
      boost::make_assoc_property_map(weights),
      boost::make_assoc_property_map(coupling_map),
      boost::make_assoc_property_map(cs_xs),
      boost::make_assoc_property_map(cs_ty));

   for (std::pair<VertexIter,VertexIter> vpx=boost::vertices(g);
      vpx.first!=vpx.second; vpx.first++)
   {
      Vertex v_x = *vpx.first;
      for (std::pair<VertexIter,VertexIter> vpy=boost::vertices(g);
         vpy.first!=vpy.second; vpy.first++)
      {
         Vertex v_y = *vpy.first;
         printf("coupling: %f\n",
            coupling_map[std::make_pair(v_x,v_y)]);
      }
   }

   ASSERT_EQ(1.0, coupling_map[std::make_pair(v,v)]);
}

// single directed edge
TEST(PartitionAllTestCase, SingleDirectedEdgeTest)
{
   typedef boost::adjacency_list<
      boost::vecS, // Edgelist ds, for per-vertex out-edges
      boost::vecS, // VertexList ds, for vertex set
      boost::directedS // type of graph
      > Graph;
   typedef boost::graph_traits<Graph> GraphTypes;
   typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
   typedef boost::graph_traits<Graph>::vertex_iterator VertexIter;
   typedef boost::graph_traits<Graph>::edge_descriptor Edge;
   typedef boost::graph_traits<Graph>::edge_iterator EdgeIter;
   typedef boost::graph_traits<Graph>::out_edge_iterator EdgeOutIter;
   typedef boost::graph_traits<Graph>::in_edge_iterator EdgeInIter;

   printf("starting test 2 (single directed edge):\n");

   Graph g;

   // add vertices
   Vertex v1 = boost::add_vertex(g);
   Vertex v2 = boost::add_vertex(g);
   std::map<Vertex, std::string> v_names;
   v_names[v1] = "v1";
   v_names[v2] = "v2";

   // add edges
   Edge e12 = boost::add_edge(v1, v2, g).first;
   std::map<Edge,double> weights;
   weights[e12] = 1.0;

   // output, temp
   std::map<std::pair<Vertex,Vertex>, double> coupling_map;
   std::map<Vertex, double> cs_xs;
   std::map<Vertex, double> cs_ty;

   pr_bgl::partition_all(g, 1.0,
      boost::make_assoc_property_map(weights),
      boost::make_assoc_property_map(coupling_map),
      boost::make_assoc_property_map(cs_xs),
      boost::make_assoc_property_map(cs_ty));

   for (std::pair<VertexIter,VertexIter> vpx=boost::vertices(g);
      vpx.first!=vpx.second; vpx.first++)
   {
      Vertex v_x = *vpx.first;
      for (std::pair<VertexIter,VertexIter> vpy=boost::vertices(g);
         vpy.first!=vpy.second; vpy.first++)
      {
         Vertex v_y = *vpy.first;
         printf("coupling %s->%s: %f\n",
            v_names[v_x].c_str(), v_names[v_y].c_str(),
            coupling_map[std::make_pair(v_x,v_y)]);
      }
   }

   ASSERT_EQ(1.0, coupling_map[std::make_pair(v1,v1)]);
   ASSERT_EQ(exp(-1.0), coupling_map[std::make_pair(v1,v2)]);
   ASSERT_EQ(0.0, coupling_map[std::make_pair(v2,v1)]);
   ASSERT_EQ(1.0, coupling_map[std::make_pair(v2,v2)]);

   // remove the edge
   printf("attempt removing edge ...\n");
   pr_bgl::partition_all_update_edge(g, e12, 1.0, false,
      boost::make_assoc_property_map(coupling_map),
      boost::make_assoc_property_map(cs_xs),
      boost::make_assoc_property_map(cs_ty));

   for (std::pair<VertexIter,VertexIter> vpx=boost::vertices(g);
      vpx.first!=vpx.second; vpx.first++)
   {
      Vertex v_x = *vpx.first;
      for (std::pair<VertexIter,VertexIter> vpy=boost::vertices(g);
         vpy.first!=vpy.second; vpy.first++)
      {
         Vertex v_y = *vpy.first;
         printf("coupling %s->%s: %f\n",
            v_names[v_x].c_str(), v_names[v_y].c_str(),
            coupling_map[std::make_pair(v_x,v_y)]);
      }
   }

   ASSERT_EQ(1.0, coupling_map[std::make_pair(v1,v1)]);
   ASSERT_EQ(0.0, coupling_map[std::make_pair(v1,v2)]);
   ASSERT_EQ(0.0, coupling_map[std::make_pair(v2,v1)]);
   ASSERT_EQ(1.0, coupling_map[std::make_pair(v2,v2)]);
}

// double directed edges
TEST(PartitionAllTestCase, DoubleDirectedEdgesTest)
{
   typedef boost::adjacency_list<
      boost::vecS, // Edgelist ds, for per-vertex out-edges
      boost::vecS, // VertexList ds, for vertex set
      boost::directedS // type of graph
      > Graph;
   typedef boost::graph_traits<Graph> GraphTypes;
   typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
   typedef boost::graph_traits<Graph>::vertex_iterator VertexIter;
   typedef boost::graph_traits<Graph>::edge_descriptor Edge;
   typedef boost::graph_traits<Graph>::edge_iterator EdgeIter;
   typedef boost::graph_traits<Graph>::out_edge_iterator EdgeOutIter;
   typedef boost::graph_traits<Graph>::in_edge_iterator EdgeInIter;

   printf("starting test 3 (double directed edges):\n");

   Graph g;

   // add vertices
   Vertex v1 = boost::add_vertex(g);
   Vertex v2 = boost::add_vertex(g);
   std::map<Vertex, std::string> v_names;
   v_names[v1] = "v1";
   v_names[v2] = "v2";

   // add edges
   Edge e12 = boost::add_edge(v1, v2, g).first;
   Edge e21 = boost::add_edge(v2, v1, g).first;
   std::map<Edge,double> weights;
   weights[e12] = 1.0;
   weights[e21] = 1.0;

   // output, temp
   std::map<std::pair<Vertex,Vertex>, double> coupling_map;
   std::map<Vertex, double> cs_xs;
   std::map<Vertex, double> cs_ty;

   pr_bgl::partition_all(g, 1.0,
      boost::make_assoc_property_map(weights),
      boost::make_assoc_property_map(coupling_map),
      boost::make_assoc_property_map(cs_xs),
      boost::make_assoc_property_map(cs_ty));

   for (std::pair<VertexIter,VertexIter> vpx=boost::vertices(g);
      vpx.first!=vpx.second; vpx.first++)
   {
      Vertex v_x = *vpx.first;
      for (std::pair<VertexIter,VertexIter> vpy=boost::vertices(g);
         vpy.first!=vpy.second; vpy.first++)
      {
         Vertex v_y = *vpy.first;
         printf("coupling %s->%s: %f\n",
            v_names[v_x].c_str(), v_names[v_y].c_str(),
            coupling_map[std::make_pair(v_x,v_y)]);
      }
   }

   double e = exp(1.0);
   ASSERT_EQ(1.+1./(e*e-1.), coupling_map[std::make_pair(v1,v1)]);
   ASSERT_EQ(e/(e*e-1.), coupling_map[std::make_pair(v1,v2)]);
   ASSERT_EQ(e/(e*e-1.), coupling_map[std::make_pair(v2,v1)]);
   ASSERT_EQ(1.+1./(e*e-1.), coupling_map[std::make_pair(v2,v2)]);

   // remove the edge
   printf("attempt removing both edges ...\n");
   pr_bgl::partition_all_update_edge(g, e12, 1.0, false,
      boost::make_assoc_property_map(coupling_map),
      boost::make_assoc_property_map(cs_xs),
      boost::make_assoc_property_map(cs_ty));
   pr_bgl::partition_all_update_edge(g, e21, 1.0, false,
      boost::make_assoc_property_map(coupling_map),
      boost::make_assoc_property_map(cs_xs),
      boost::make_assoc_property_map(cs_ty));

   for (std::pair<VertexIter,VertexIter> vpx=boost::vertices(g);
      vpx.first!=vpx.second; vpx.first++)
   {
      Vertex v_x = *vpx.first;
      for (std::pair<VertexIter,VertexIter> vpy=boost::vertices(g);
         vpy.first!=vpy.second; vpy.first++)
      {
         Vertex v_y = *vpy.first;
         printf("coupling %s->%s: %f\n",
            v_names[v_x].c_str(), v_names[v_y].c_str(),
            coupling_map[std::make_pair(v_x,v_y)]);
      }
   }

   ASSERT_NEAR(1.0, coupling_map[std::make_pair(v1,v1)], 1.0e-15);
   ASSERT_NEAR(0.0, coupling_map[std::make_pair(v1,v2)], 1.0e-15);
   ASSERT_NEAR(0.0, coupling_map[std::make_pair(v2,v1)], 1.0e-15);
   ASSERT_NEAR(1.0, coupling_map[std::make_pair(v2,v2)], 1.0e-15);
}

// single undirected edge
TEST(PartitionAllTestCase, SingleUndirectedEdgeTest)
{
   typedef boost::adjacency_list<
      boost::vecS, // Edgelist ds, for per-vertex out-edges
      boost::vecS, // VertexList ds, for vertex set
      boost::undirectedS // type of graph
      > Graph;
   typedef boost::graph_traits<Graph> GraphTypes;
   typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
   typedef boost::graph_traits<Graph>::vertex_iterator VertexIter;
   typedef boost::graph_traits<Graph>::edge_descriptor Edge;
   typedef boost::graph_traits<Graph>::edge_iterator EdgeIter;
   typedef boost::graph_traits<Graph>::out_edge_iterator EdgeOutIter;
   typedef boost::graph_traits<Graph>::in_edge_iterator EdgeInIter;

   printf("starting test 4 (single undirected edge):\n");

   Graph g;

   // add vertices
   Vertex v1 = boost::add_vertex(g);
   Vertex v2 = boost::add_vertex(g);
   std::map<Vertex, std::string> v_names;
   v_names[v1] = "v1";
   v_names[v2] = "v2";

   // add edges
   Edge e12 = boost::add_edge(v1, v2, g).first;
   std::map<Edge,double> weights;
   weights[e12] = 1.0;

   // output, temp
   std::map<std::pair<Vertex,Vertex>, double> coupling_map;
   std::map<Vertex, double> cs_xs;
   std::map<Vertex, double> cs_ty;

   pr_bgl::partition_all(g, 1.0,
      boost::make_assoc_property_map(weights),
      boost::make_assoc_property_map(coupling_map),
      boost::make_assoc_property_map(cs_xs),
      boost::make_assoc_property_map(cs_ty));

   for (std::pair<VertexIter,VertexIter> vpx=boost::vertices(g);
      vpx.first!=vpx.second; vpx.first++)
   {
      Vertex v_x = *vpx.first;
      for (std::pair<VertexIter,VertexIter> vpy=boost::vertices(g);
         vpy.first!=vpy.second; vpy.first++)
      {
         Vertex v_y = *vpy.first;
         printf("coupling %s->%s: %f\n",
            v_names[v_x].c_str(), v_names[v_y].c_str(),
            coupling_map[std::make_pair(v_x,v_y)]);
      }
   }

   double e = exp(1.0);
   ASSERT_EQ(1.+1./(e*e-1.), coupling_map[std::make_pair(v1,v1)]);
   ASSERT_EQ(e/(e*e-1.), coupling_map[std::make_pair(v1,v2)]);
   ASSERT_EQ(e/(e*e-1.), coupling_map[std::make_pair(v2,v1)]);
   ASSERT_EQ(1.+1./(e*e-1.), coupling_map[std::make_pair(v2,v2)]);

   // remove the edge
   printf("attempt removing edge ...\n");
   pr_bgl::partition_all_update_edge(g, e12, 1.0, false,
      boost::make_assoc_property_map(coupling_map),
      boost::make_assoc_property_map(cs_xs),
      boost::make_assoc_property_map(cs_ty));

   for (std::pair<VertexIter,VertexIter> vpx=boost::vertices(g);
      vpx.first!=vpx.second; vpx.first++)
   {
      Vertex v_x = *vpx.first;
      for (std::pair<VertexIter,VertexIter> vpy=boost::vertices(g);
         vpy.first!=vpy.second; vpy.first++)
      {
         Vertex v_y = *vpy.first;
         printf("coupling %s->%s: %f\n",
            v_names[v_x].c_str(), v_names[v_y].c_str(),
            coupling_map[std::make_pair(v_x,v_y)]);
      }
   }

   ASSERT_NEAR(1.0, coupling_map[std::make_pair(v1,v1)], 1.0e-15);
   ASSERT_NEAR(0.0, coupling_map[std::make_pair(v1,v2)], 1.0e-15);
   ASSERT_NEAR(0.0, coupling_map[std::make_pair(v2,v1)], 1.0e-15);
   ASSERT_NEAR(1.0, coupling_map[std::make_pair(v2,v2)], 1.0e-15);
}

int main(int argc, char **argv)
{
   testing::InitGoogleTest(&argc, argv);
   return RUN_ALL_TESTS();
}


text:
from datetime import datetime

import mock
from nose.tools import eq_, ok_

from mkt.constants.base import STATUS_PENDING, STATUS_PUBLIC
from mkt.site.tests import ESTestCase, TestCase
from mkt.extensions.indexers import ExtensionIndexer
from mkt.extensions.models import Extension, ExtensionVersion
from mkt.search.utils import BOOST_MULTIPLIER_FOR_PUBLIC_CONTENT, get_boost

class TestExtensionIndexer(TestCase):

    def setUp(self):
        self.indexer = Extension.get_indexer()()

    def _extension_factory(self, status=STATUS_PENDING, reviewed=None):
        if reviewed is None:
            # Microseconds are not saved by MySQL, so set it to 0 to make sure
            # our comparisons still work once the model is saved to the db.
            reviewed = datetime.utcnow().replace(microsecond=0)
        extension = Extension.objects.create(
            author=u'Test Aùthor', description=u'Test Desçription',
            name=u'Test Êxtension', last_updated=reviewed,
            slug=u'test-ëxtension')
        version = ExtensionVersion.objects.create(
            extension=extension, size=42, status=status, reviewed=reviewed,
            version='0.1')
        return extension, version

    def test_model(self):
        eq_(self.indexer.get_model(), Extension)
        ok_(isinstance(self.indexer, ExtensionIndexer))

    def test_get_mapping_ok(self):
        eq_(ExtensionIndexer.get_mapping_type_name(), 'extension')
        ok_(isinstance(self.indexer.get_mapping(), dict))

    def test_index(self):
        with self.settings(ES_INDEXES={'extension': 'extensions'}):
            eq_(ExtensionIndexer.get_index(), 'extensions')

    def test_mapping(self):
        mapping = ExtensionIndexer.get_mapping()
        eq_(mapping.keys(), ['extension'])
        eq_(mapping['extension']['_all'], {'enabled': False})

    def _get_doc(self, extension):
        return self.indexer.extract_document(extension.pk, extension)

    def test_extract_dont_pass_obj(self):
        extension, version = self._extension_factory()
        doc = self.indexer.extract_document(extension.pk)
        eq_(doc['id'], extension.id)

    def test_extract_not_public(self):
        extension, version = self._extension_factory()
        doc = self._get_doc(extension)
        eq_(doc['id'], extension.id)
        eq_(doc['status'], extension.status)
        eq_(doc['latest_public_version'], None)

    def test_extract_disabled(self):
        extension, version = self._extension_factory(STATUS_PUBLIC)
        extension.update(disabled=True)
        doc = self._get_doc(extension)
        eq_(doc['id'], extension.id)
        eq_(doc['is_disabled'], True)
        eq_(doc['status'], STATUS_PUBLIC)
        eq_(doc['latest_public_version'],
            {'id': version.pk,
             'created': version.created.replace(microsecond=0),
             'size': 42, 'version': '0.1', })

    def test_extract_public(self):
        extension, version = self._extension_factory(STATUS_PUBLIC)
        doc = self._get_doc(extension)
        eq_(doc['id'], extension.id)
        eq_(doc['author'], extension.author)
        eq_(doc['created'], extension.created)
        eq_(doc['description'], [unicode(extension.description)])
        eq_(doc['description_translations'], [{
            'lang': u'en-US', 'string': unicode(extension.description)}])
        eq_(doc['default_language'], extension.default_language)
        eq_(doc['device'], extension.devices)
        eq_(doc['guid'], extension.uuid)
        eq_(doc['is_disabled'], extension.disabled)
        eq_(doc['last_updated'], extension.last_updated)
        eq_(doc['modified'], extension.modified)
        eq_(doc['name'], [unicode(extension.name)])
        eq_(doc['name_translations'], [{
            'lang': u'en-US', 'string': unicode(extension.name)}])
        eq_(doc['reviewed'], version.reviewed)
        eq_(doc['slug'], extension.slug)
        eq_(doc['status'], extension.status)
        eq_(doc['latest_public_version'],
            {'id': version.pk,
             'created': version.created.replace(microsecond=0),
             'size': 42, 'version': '0.1', })

    def test_reviewed_multiple_versions(self):
        extension, first_public_version = self._extension_factory(
            STATUS_PUBLIC, reviewed=self.days_ago(3))
        ExtensionVersion.objects.create(
            extension=extension, size=42, status=STATUS_PUBLIC,
            reviewed=self.days_ago(2), version='0.2')
        ExtensionVersion.objects.create(
            extension=extension, size=42, status=STATUS_PENDING,
            reviewed=self.days_ago(1), version='0.3')
        doc = self._get_doc(extension)
        eq_(doc['id'], extension.id)
        eq_(doc['reviewed'], first_public_version.reviewed)

    def test_extract_with_translations(self):
        extension, version = self._extension_factory()
        description = {
            'en-US': u'Description Extensiôn',
            'fr': u"Description de l'Ëxtension",
        }
        name = {
            'en-US': u'Namé Extension',
            'fr': u"Nom de l'Ëxtension",
        }
        extension.description = description
        extension.name = name
        extension.save()
        doc = self._get_doc(extension)

        eq_(sorted(doc['name']), [name['en-US'], name['fr']])
        eq_(sorted(doc['name_translations']),
            [{'lang': 'en-US', 'string': name['en-US']},
             {'lang': 'fr', 'string': name['fr']}])
        eq_(doc['name_l10n_french'], [name['fr']])
        eq_(doc['name_l10n_english'], [name['en-US']])
        eq_(doc['name_sort'], name['en-US'].lower())

        eq_(sorted(doc['description']),
            [description['en-US'], description['fr']])
        eq_(sorted(doc['description_translations']),
            [{'lang': 'en-US', 'string': description['en-US']},
             {'lang': 'fr', 'string': description['fr']}])
        eq_(doc['description_l10n_french'], [description['fr']])
        eq_(doc['description_l10n_english'], [description['en-US']])
        ok_('description_sort' not in doc)

    @mock.patch('mkt.search.indexers.MATURE_REGION_IDS', [42])
    def test_popularity(self):
        extension, version = self._extension_factory()
        # No installs.
        doc = self._get_doc(extension)
        # Boost is multiplied by BOOST_MULTIPLIER_FOR_PUBLIC_CONTENT if it's
        # public.
        eq_(doc['boost'], 1.0 * BOOST_MULTIPLIER_FOR_PUBLIC_CONTENT)
        eq_(doc['popularity'], 0)

        # Add some popularity.
        extension.popularity.create(region=0, value=50.0)
        # Test an adolescent region.
        extension.popularity.create(region=2, value=10.0)
        # Test a mature region.
        extension.popularity.create(region=42, value=10.0)

        doc = self._get_doc(extension)
        eq_(doc['boost'], get_boost(extension))
        eq_(doc['popularity'], 50)
        eq_(doc['popularity_42'], 10)
        # Adolescent regions popularity value is not stored.
        ok_('popularity_2' not in doc)

    @mock.patch('mkt.search.indexers.MATURE_REGION_IDS', [42])
    def test_trending(self):
        extension, version = self._extension_factory()
        extension.trending.create(region=0, value=10.0)
        # Test an adolescent region.
        extension.trending.create(region=2, value=50.0)
        # Test a mature region.
        extension.trending.create(region=42, value=50.0)

        doc = self._get_doc(extension)
        eq_(doc['trending'], 10.0)
        eq_(doc['trending_42'], 50.0)

        # Adolescent regions trending value is not stored.
        ok_('trending_2' not in doc)

class TestExtensionIndexerExcludedFields(ESTestCase):
    def setUp(self):
        super(TestExtensionIndexerExcludedFields, self).setUp()
        self.extension = Extension.objects.create()
        self.extension.trending.create(region=2, value=50.0)
        self.extension.popularity.create(region=2, value=142.0)
        self.refresh('extension')

    def test_excluded_fields(self):
        ok_(ExtensionIndexer.hidden_fields)

        data = ExtensionIndexer.search().execute().hits
        eq_(len(data), 1)
        obj = data[0]

        ok_('name_translations' in obj)
        ok_('name' not in obj)
        ok_('name_l10n_english' not in obj)
        ok_('name_sort' not in obj)
        ok_('name.raw' not in obj)

        ok_('trending_2' not in obj)
        ok_('popularity_2' not in obj)
        ok_('boost' not in obj)

        ok_('description_translations' in obj)
        ok_('description' not in obj)
        ok_('description_l10n_english' not in obj)

class TestExtensionIndexerBasicSearch(ESTestCase):
    def test_search_basic(self, status=STATUS_PENDING):
        extension = Extension.objects.create(
            name=u'Test Êxtension', slug=u'test-ëxtension')
        ExtensionVersion.objects.create(
            extension=extension, status=status, version='0.1')
        self.reindex(Extension)

        qs = ExtensionIndexer.search()
        results = qs.execute().hits
        eq_(len(results), 1)
        eq_(results.hits[0]['_id'], unicode(extension.pk))


text:
using Lucene.Net.Index;
using Lucene.Net.Queries.Function;
using Lucene.Net.Queries.Function.DocValues;
using Lucene.Net.Search;
using Spatial4n.Core.Context;
using Spatial4n.Core.Distance;
using Spatial4n.Core.Shapes;
using System.Collections;

namespace Lucene.Net.Spatial.Util
{

    /// <summary>
    /// The distance from a provided Point to a Point retrieved from a ValueSource via
    /// <see cref="FunctionValues.ObjectVal(int)"/>. The distance
    /// is calculated via a <see cref="IDistanceCalculator"/>.
    ///
    /// @lucene.experimental
    /// </summary>
    public class DistanceToShapeValueSource : ValueSource
    {
        private readonly ValueSource shapeValueSource;
        private readonly IPoint queryPoint;
        private readonly double multiplier;
        private readonly IDistanceCalculator distCalc;

        //TODO if FunctionValues returns NaN; will things be ok?
        private readonly double nullValue;//computed

        public DistanceToShapeValueSource(ValueSource shapeValueSource, IPoint queryPoint,
                                          double multiplier, SpatialContext ctx)
        {
            this.shapeValueSource = shapeValueSource;
            this.queryPoint = queryPoint;
            this.multiplier = multiplier;
            this.distCalc = ctx.DistCalc;
            this.nullValue =
                (ctx.IsGeo ? 180 * multiplier : double.MaxValue);
        }

        public override string GetDescription()
        {
            return "distance(" + queryPoint + " to " + shapeValueSource.GetDescription() + ")*" + multiplier + ")";
        }

        public override void CreateWeight(IDictionary context, IndexSearcher searcher)
        {
            shapeValueSource.CreateWeight(context, searcher);
        }

        public override FunctionValues GetValues(IDictionary context, AtomicReaderContext readerContext)
        {
            FunctionValues shapeValues = shapeValueSource.GetValues(context, readerContext);

            return new DoubleDocValuesAnonymousHelper(this, shapeValues);
        }

        internal class DoubleDocValuesAnonymousHelper : DoubleDocValues
        {
            private readonly DistanceToShapeValueSource outerInstance;
            private readonly FunctionValues shapeValues;

            public DoubleDocValuesAnonymousHelper(DistanceToShapeValueSource outerInstance, FunctionValues shapeValues)
                : base(outerInstance)
            {
                this.outerInstance = outerInstance;
                this.shapeValues = shapeValues;
            }

            public override double DoubleVal(int doc)
            {
                IShape shape = (IShape)shapeValues.ObjectVal(doc);
                if (shape == null || shape.IsEmpty)
                    return outerInstance.nullValue;
                IPoint pt = shape.Center;
                return outerInstance.distCalc.Distance(outerInstance.queryPoint, pt) * outerInstance.multiplier;
            }

            public override Explanation Explain(int doc)
            {
                Explanation exp = base.Explain(doc);
                exp.AddDetail(shapeValues.Explain(doc));
                return exp;
            }
        }

        public override bool Equals(object o)
        {
            if (this == o) return true;
            if (o == null || GetType() != o.GetType()) return false;

            DistanceToShapeValueSource that = (DistanceToShapeValueSource)o;

            if (!queryPoint.Equals(that.queryPoint)) return false;
            if (that.multiplier.CompareTo(multiplier) != 0) return false;
            if (!shapeValueSource.Equals(that.shapeValueSource)) return false;
            if (!distCalc.Equals(that.distCalc)) return false;

            return true;
        }

        public override int GetHashCode()
        {
            int result;
            long temp;
            result = shapeValueSource.GetHashCode();
            result = 31 * result + queryPoint.GetHashCode();
            temp = J2N.BitConversion.DoubleToInt64Bits(multiplier);
            result = 31 * result + (int)(temp ^ ((long)((ulong)temp) >> 32));
            return result;
        }
    }
}


text:
mpf.platform.fadecandy module
=============================

.. automodule:: mpf.platform.fadecandy
    :members:
    :undoc-members:
    :show-inheritance:


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

public class CatAttack : MonoBehaviour {

    Animator anim;
    public AudioSource CatAttackSource;
    public AudioSource CatSkillSource;
    public AudioSource CatUtimateSource;

    public AudioClip CatAttackClip;
    public AudioClip CatSkillClip;
    public AudioClip CatUtimateClip;

    public KeyCode melee;
    public KeyCode skill;
    public KeyCode ultimate;

    public GameObject meleeCheck;
    public GameObject skillObject;
    public Transform skillPos;
    public GameObject ultimateCollider;
    public float meleeAttackDelay = 0.3f;
    public Transform catUltimatePos1;
    public Transform catUltimatePos2;
    public GameObject ultimateObject;

    ParticleSystem ultimateParticle;
    public float meleeAtaackResetTime = 0.7f;
    public float dashAttackTime = 0.7f;
    public float skillCastingTime = 0.7f;
    public float coolTime = 6f;

    float skillCoolTime = 6f;
    bool isCasting = false;
    float ultimateGauge = 1000;
    public float UltimateGauge { get { return Mathf.Min(1000, ultimateGauge); } set { ultimateGauge = value; } }
    float speedTemp;
    bool isSkillShooting;

    GameObject newSkill;
    GameObject newUltimate1;
    GameObject newUltimate2;

    void Start ()
    {
        speedTemp = GetComponent<CharacterControll>().moveSpeed;
        ultimateParticle = GetComponent<ParticleSystem>();
        anim = GetComponent<Animator>();
        CatAttackSource.clip = CatAttackClip;
        CatSkillSource.clip = CatSkillClip;
        CatUtimateSource.clip = CatUtimateClip;

    }

	// Update is called once per frame
	void Update () {

        if (GetComponent<CharacterControll>().enabled)
        {
            skillCoolTime += Time.deltaTime;
            if (UltimateGauge == 1000 && !ultimateParticle.isPlaying)
            {
                ultimateParticle.Play();
            }
            else if (UltimateGauge < 1000)
            {
                ultimateParticle.Stop();
            }

            if (Input.GetKeyDown(melee))
            {
                Melee(100f, 7, new Vector2(transform.localScale.x, 0));
                anim.Play("Cat_Melee");
                CatAttackSource.Play();
            }
            if (Input.GetKeyDown(skill) && skillCoolTime > coolTime && GetComponent<CharacterControll>().IsOnFloor())
            {
                skillCoolTime = 0;
                StartCoroutine(SkillCasting());
                anim.Play("Cat_Skill");
                CatSkillSource.Play();
            }
            if (Input.GetKeyDown(ultimate) && UltimateGauge == 1000)
            {
                StartCoroutine(UltimateCastingDelay());
                anim.Play("Cat_Ultimate");
                CatUtimateSource.Play();
            }

            if (isCasting)
            {
                GetComponent<CharacterControll>().moveSpeed = 0;
                GetComponent<CharacterControll>().isCasting = true;
                if (GetComponent<CharacterControll>().hit)
                {
                    CancelCasting();
                    StopAllCoroutines();
                }
            }
            else
            {
                GetComponent<CharacterControll>().moveSpeed = speedTemp;
                GetComponent<CharacterControll>().isCasting = false;
            }
        }

        updateUltGauge();
    }

    void updateUltGauge()
    {
        GetComponent<CharacterControll>().ult = UltimateGauge;
    }

    IEnumerator UltimateCastingDelay()
    {
        yield return new WaitForSeconds(0.15f);
        Ultimate();
    }

    void Ultimate()
    {
        UltimateGauge = 0;
        newUltimate1 = Instantiate(ultimateObject, catUltimatePos1.position, Quaternion.identity);
        newUltimate2 = Instantiate(ultimateObject, catUltimatePos2.position, Quaternion.identity);
        if (this.transform.localScale.x <= 0)
        {
            newUltimate1.transform.localScale = new Vector3(-1, 1, 1);
        }
        else if (this.transform.localScale.x >0)
        {
            newUltimate2.transform.localScale = new Vector3(-1, 1, 1);
        }

        if (ultimateCollider.GetComponent<MeleeCheck>().playersInRange.Count != 0)
        {
            foreach (GameObject player in ultimateCollider.GetComponent<MeleeCheck>().playersInRange)
            {
                int direction = (int)((player.transform.position.x - transform.position.x) / Mathf.Abs(player.transform.position.x - transform.position.x));
                player.GetComponent<CharacterControll>().Hit(250f, 20, new Vector2(direction, 0));
            }
        }

        StartCoroutine(UltimateAnimation());
    }

    void Melee(float damage, int attack, Vector2 knockBackDirection)
    {
        if (meleeCheck.GetComponent<MeleeCheck>().playersInRange.Count != 0)
        {
            foreach (GameObject player in meleeCheck.GetComponent<MeleeCheck>().playersInRange)
            {
                UltimateGauge += damage;
                player.GetComponent<CharacterControll>().Hit(damage, attack, knockBackDirection);
            }
        }
    }

    void CancelCasting()
    {
        if (isCasting)
        {
            if (newSkill != null)
            {
                Destroy(newSkill);
            }
            isCasting = false;
        }
    }

    void Skill()
    {

        foreach (var player in newSkill.GetComponent<MeleeCheck>().playersInRange)
        {
            player.GetComponent<CharacterControll>().hit = true;
            player.GetComponent<CharacterControll>().Hit(150f, 10, new Vector2(transform.localScale.x,0));
        }
    }

    IEnumerator SkillCasting()
    {
        isCasting = true;
        yield return new WaitForSeconds(skillCastingTime);
        newSkill = Instantiate(skillObject, skillPos.position, Quaternion.identity, this.transform);
        yield return new WaitForSeconds(0.1f);
        Skill();
        yield return new WaitForSeconds(0.9f);
        isCasting = false;
        if (newSkill != null)
        {
            Destroy(newSkill);
        }
    }

    IEnumerator UltimateAnimation()
    {
        yield return new WaitForSeconds(1f);

        if (newUltimate1 != null && newUltimate2 != null)
        {
            Destroy(newUltimate1);
            Destroy(newUltimate2);
        }

    }
}


text:
package apikit
import (
	"github.com/revel/revel"
	"encoding/json"
	"net/http"
)

type GETHooker interface {
	RESTController
	PreGETHook(id uint64, authUser User) revel.Result
	PostGETHook(model RESTObject, authUser User) revel.Result
}

type POSTHooker interface {
	RESTController
	PrePOSTHook(model RESTObject, authUser User) revel.Result
	PostPOSTHook(model RESTObject, authUser User, err error) revel.Result
}

type PUTHooker interface {
	RESTController
	PrePUTHook(newInstance, existingInstance RESTObject, authUser User) revel.Result
	PostPUTHook(newInstance, existingInstance RESTObject, authUser User, err error) revel.Result
}

type DELETEHooker interface {
	RESTController
	PreDELETEHook(model RESTObject, authUser User) revel.Result
	PostDELETEHook(model RESTObject, authUser User, err error) revel.Result
}

// Result that can be returned from a hook
type HookJsonResult struct {
	Body interface{}
}

func (result HookJsonResult) Apply(req *revel.Request, resp *revel.Response) {
	if body, err := json.Marshal(result.Body); err != nil {
		ApiMessage{
			StatusCode: http.StatusInternalServerError,
			Message: "Something went wrong",
		}.Apply(req, resp)
	} else {
		resp.WriteHeader(http.StatusOK, "application/json")
		resp.Out.Write(body)
	}
}


text:
var gulp = require('gulp');
var to5 = require('gulp-babel');
var mocha = require('gulp-mocha');
var webpack = require('gulp-webpack');

gulp.task('build', function() {
  return gulp.src('src/**/*.js')
    .pipe(to5({stage: 1, optional: 'runtime'}))
    .pipe(gulp.dest('dist'));
});

gulp.task('test', function() {
  require("babel/register")({
    stage: 1, optional: 'runtime'
  });

  return gulp.src('tests/**/*test.js')
    .pipe(mocha({reporter: 'nyan'}));
});

gulp.task('webpack', function() {
  var myConfig = Object.create(require('./webpack.config'));

  return gulp.src('src/')
    .pipe(webpack(myConfig))
    .pipe(gulp.dest('./'));
});


text:
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <linux/of_gpio.h>

#include <sound/core.h>
#include <sound/jack.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>

#define DRV_NAME "tegra-snd-wm9712"

struct tegra_wm9712 {
	struct platform_device *codec;
};

static const struct snd_soc_dapm_widget tegra_wm9712_dapm_widgets[] = {
	SND_SOC_DAPM_HP("Headphone", NULL),
	SND_SOC_DAPM_LINE("LineIn", NULL),
	SND_SOC_DAPM_MIC("Mic", NULL),
};

static int tegra_wm9712_init(struct snd_soc_pcm_runtime *rtd)
{
	struct snd_soc_dai *codec_dai = rtd->codec_dai;
	struct snd_soc_codec *codec = codec_dai->codec;
	struct snd_soc_dapm_context *dapm = &codec->dapm;

	snd_soc_dapm_force_enable_pin(dapm, "Mic Bias");

	return snd_soc_dapm_sync(dapm);
}

static struct snd_soc_dai_link tegra_wm9712_dai = {
	.name = "AC97 HiFi",
	.stream_name = "AC97 HiFi",
	.codec_dai_name = "wm9712-hifi",
	.codec_name = "wm9712-codec",
	.init = tegra_wm9712_init,
};

static struct snd_soc_card snd_soc_tegra_wm9712 = {
	.name = "tegra-wm9712",
	.owner = THIS_MODULE,
	.dai_link = &tegra_wm9712_dai,
	.num_links = 1,

	.dapm_widgets = tegra_wm9712_dapm_widgets,
	.num_dapm_widgets = ARRAY_SIZE(tegra_wm9712_dapm_widgets),
	.fully_routed = true,
};

static int tegra_wm9712_driver_probe(struct platform_device *pdev)
{
	struct device_node *np = pdev->dev.of_node;
	struct snd_soc_card *card = &snd_soc_tegra_wm9712;
	struct tegra_wm9712 *machine;
	int ret;

	machine = devm_kzalloc(&pdev->dev, sizeof(struct tegra_wm9712),
			       GFP_KERNEL);
	if (!machine) {
		dev_err(&pdev->dev, "Can't allocate tegra_wm9712 struct\n");
		return -ENOMEM;
	}

	card->dev = &pdev->dev;
	platform_set_drvdata(pdev, card);
	snd_soc_card_set_drvdata(card, machine);

	machine->codec = platform_device_alloc("wm9712-codec", -1);
	if (!machine->codec) {
		dev_err(&pdev->dev, "Can't allocate wm9712 platform device\n");
		return -ENOMEM;
	}

	ret = platform_device_add(machine->codec);
	if (ret)
		goto codec_put;

	ret = snd_soc_of_parse_card_name(card, "nvidia,model");
	if (ret)
		goto codec_unregister;

	ret = snd_soc_of_parse_audio_routing(card, "nvidia,audio-routing");
	if (ret)
		goto codec_unregister;

	tegra_wm9712_dai.cpu_of_node = of_parse_phandle(np,
				       "nvidia,ac97-controller", 0);
	if (!tegra_wm9712_dai.cpu_of_node) {
		dev_err(&pdev->dev,
			"Property 'nvidia,ac97-controller' missing or invalid\n");
		ret = -EINVAL;
		goto codec_unregister;
	}

	tegra_wm9712_dai.platform_of_node = tegra_wm9712_dai.cpu_of_node;

	ret = snd_soc_register_card(card);
	if (ret) {
		dev_err(&pdev->dev, "snd_soc_register_card failed (%d)\n",
			ret);
		goto codec_unregister;
	}

	return 0;

codec_unregister:
	platform_device_del(machine->codec);
codec_put:
	platform_device_put(machine->codec);
	return ret;
}

static int tegra_wm9712_driver_remove(struct platform_device *pdev)
{
	struct snd_soc_card *card = platform_get_drvdata(pdev);
	struct tegra_wm9712 *machine = snd_soc_card_get_drvdata(card);

	snd_soc_unregister_card(card);

	platform_device_unregister(machine->codec);

	return 0;
}

static const struct of_device_id tegra_wm9712_of_match[] = {
	{ .compatible = "nvidia,tegra-audio-wm9712", },
	{},
};

static struct platform_driver tegra_wm9712_driver = {
	.driver = {
		.name = DRV_NAME,
		.owner = THIS_MODULE,
		.pm = &snd_soc_pm_ops,
		.of_match_table = tegra_wm9712_of_match,
	},
	.probe = tegra_wm9712_driver_probe,
	.remove = tegra_wm9712_driver_remove,
};
module_platform_driver(tegra_wm9712_driver);

MODULE_AUTHOR("Lucas Stach");
MODULE_DESCRIPTION("Tegra+WM9712 machine ASoC driver");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:" DRV_NAME);
MODULE_DEVICE_TABLE(of, tegra_wm9712_of_match);


text:
@interface NSArray(Extension)

+(instancetype)getAllProperties:(Class )aClass;

+(instancetype)getAllIvars:(Class) aClass;

@end