text:
(function() {
  'use strict';
  /**
   * Creates and maintains a synchronized object, with 2-way bindings between Angular and Firebase.
   *
   * Implementations of this class are contracted to provide the following internal methods,
   * which are used by the synchronization process and 3-way bindings:
   *    $$updated - called whenever a change occurs (a value event from Firebase)
   *    $$error - called when listeners are canceled due to a security error
   *    $$notify - called to update $watch listeners and trigger updates to 3-way bindings
   *    $ref - called to obtain the underlying Firebase reference
   *
   * Instead of directly modifying this class, one should generally use the $extend
   * method to add or change how methods behave:
   *
   *

   * var ExtendedObject = $firebaseObject.$extend({
   *    // add a new method to the prototype
   *    foo: function() { return 'bar'; },
   * });
   *
   * var obj = new ExtendedObject(ref);
   *

   */
  angular.module('firebase.database').factory('$firebaseObject', [
    '$parse', '$firebaseUtils', '$log', '$q',
    function($parse, $firebaseUtils, $log, $q) {
      /**
       * Creates a synchronized object with 2-way bindings between Angular and Firebase.
       *
       * @param {Firebase} ref
       * @returns {FirebaseObject}
       * @constructor
       */
      function FirebaseObject(ref) {
        if( !(this instanceof FirebaseObject) ) {
          return new FirebaseObject(ref);
        }
        var self = this;
        // These are private config props and functions used internally
        // they are collected here to reduce clutter in console.log and forEach
        this.$$conf = {
          // synchronizes data to Firebase
          sync: new ObjectSyncManager(this, ref),
          // stores the Firebase ref
          ref: ref,
          // synchronizes $scope variables with this object
          binding: new ThreeWayBinding(this),
          // stores observers registered with $watch
          listeners: []
        };

        // this bit of magic makes $$conf non-enumerable and non-configurable
        // and non-writable (its properties are still writable but the ref cannot be replaced)
        // we redundantly assign it above so the IDE can relax
        Object.defineProperty(this, '$$conf', {
          value: this.$$conf
        });

        this.$id = ref.ref.key;
        this.$priority = null;

        $firebaseUtils.applyDefaults(this, this.$$defaults);

        // start synchronizing data with Firebase
        this.$$conf.sync.init();

        // $resolved provides quick access to the current state of the $loaded() promise.
        // This is useful in data-binding when needing to delay the rendering or visibilty
        // of the data until is has been loaded from firebase.
        this.$resolved = false;
        this.$loaded().finally(function() {
          self.$resolved = true;
        });
      }

      FirebaseObject.prototype = {
        /**
         * Saves all data on the FirebaseObject back to Firebase.
         * @returns a promise which will resolve after the save is completed.
         */
        $save: function () {
          var self = this;
          var ref = self.$ref();
          var def = $q.defer();
          var dataJSON;

          try {
            dataJSON = $firebaseUtils.toJSON(self);
          } catch (e) {
            def.reject(e);
          }

          if (typeof dataJSON !== 'undefined') {
            $firebaseUtils.doSet(ref, dataJSON).then(function() {
              self.$$notify();
              def.resolve(self.$ref());
            }).catch(def.reject);
          }

          return def.promise;
        },

        /**
         * Removes all keys from the FirebaseObject and also removes
         * the remote data from the server.
         *
         * @returns a promise which will resolve after the op completes
         */
        $remove: function() {
          var self = this;
          $firebaseUtils.trimKeys(self, {});
          self.$value = null;
          return $firebaseUtils.doRemove(self.$ref()).then(function() {
            self.$$notify();
            return self.$ref();
          });
        },

        /**
         * The loaded method is invoked after the initial batch of data arrives from the server.
         * When this resolves, all data which existed prior to calling $asObject() is now cached
         * locally in the object.
         *
         * As a shortcut is also possible to pass resolve/reject methods directly into this
         * method just as they would be passed to .then()
         *
         * @param {Function} resolve
         * @param {Function} reject
         * @returns a promise which resolves after initial data is downloaded from Firebase
         */
        $loaded: function(resolve, reject) {
          var promise = this.$$conf.sync.ready();
          if (arguments.length) {
            // allow this method to be called just like .then
            // by passing any arguments on to .then
            promise = promise.then.call(promise, resolve, reject);
          }
          return promise;
        },

        /**
         * @returns {Firebase} the original Firebase instance used to create this object.
         */
        $ref: function () {
          return this.$$conf.ref;
        },

        /**
         * Creates a 3-way data sync between this object, the Firebase server, and a
         * scope variable. This means that any changes made to the scope variable are
         * pushed to Firebase, and vice versa.
         *
         * If scope emits a $destroy event, the binding is automatically severed. Otherwise,
         * it is possible to unbind the scope variable by using the `unbind` function
         * passed into the resolve method.
         *
         * Can only be bound to one scope variable at a time. If a second is attempted,
         * the promise will be rejected with an error.
         *
         * @param {object} scope
         * @param {string} varName
         * @returns a promise which resolves to an unbind method after data is set in scope
         */
        $bindTo: function (scope, varName) {
          var self = this;
          return self.$loaded().then(function () {
            return self.$$conf.binding.bindTo(scope, varName);
          });
        },

        /**
         * Listeners passed into this method are notified whenever a new change is received
         * from the server. Each invocation is sent an object containing
         * { type: 'value', key: 'my_firebase_id' }
         *
         * This method returns an unbind function that can be used to detach the listener.
         *
         * @param {Function} cb
         * @param {Object} [context]
         * @returns {Function} invoke to stop observing events
         */
        $watch: function (cb, context) {
          var list = this.$$conf.listeners;
          list.push([cb, context]);
          // an off function for cancelling the listener
          return function () {
            var i = list.findIndex(function (parts) {
              return parts[0] === cb && parts[1] === context;
            });
            if (i > -1) {
              list.splice(i, 1);
            }
          };
        },

        /**
         * Informs $firebase to stop sending events and clears memory being used
         * by this object (delete's its local content).
         */
        $destroy: function(err) {
          var self = this;
          if (!self.$isDestroyed) {
            self.$isDestroyed = true;
            self.$$conf.sync.destroy(err);
            self.$$conf.binding.destroy();
            $firebaseUtils.each(self, function (v, k) {
              delete self[k];
            });
          }
        },

        /**
         * Called by $firebase whenever an item is changed at the server.
         * This method must exist on any objectFactory passed into $firebase.
         *
         * It should return true if any changes were made, otherwise `$$notify` will
         * not be invoked.
         *
         * @param {object} snap a Firebase snapshot
         * @return {boolean} true if any changes were made.
         */
        $$updated: function (snap) {
          // applies new data to this object
          var changed = $firebaseUtils.updateRec(this, snap);
          // applies any defaults set using $$defaults
          $firebaseUtils.applyDefaults(this, this.$$defaults);
          // returning true here causes $$notify to be triggered
          return changed;
        },

        /**
         * Called whenever a security error or other problem causes the listeners to become
         * invalid. This is generally an unrecoverable error.
         * @param {Object} err which will have a `code` property and possibly a `message`
         */
        $$error: function (err) {
          // prints an error to the console (via Angular's logger)
          $log.error(err);
          // frees memory and cancels any remaining listeners
          this.$destroy(err);
        },

        /**
         * Called internally by $bindTo when data is changed in $scope.
         * Should apply updates to this record but should not call
         * notify().
         */
        $$scopeUpdated: function(newData) {
          // we use a one-directional loop to avoid feedback with 3-way bindings
          // since set() is applied locally anyway, this is still performant
          var def = $q.defer();
          this.$ref().set($firebaseUtils.toJSON(newData), $firebaseUtils.makeNodeResolver(def));
          return def.promise;
        },

        /**
         * Updates any bound scope variables and
         * notifies listeners registered with $watch
         */
        $$notify: function() {
          var self = this, list = this.$$conf.listeners.slice();
          // be sure to do this after setting up data and init state
          angular.forEach(list, function (parts) {
            parts[0].call(parts[1], {event: 'value', key: self.$id});
          });
        },

        /**
         * Overrides how Angular.forEach iterates records on this object so that only
         * fields stored in Firebase are part of the iteration. To include meta fields like
         * $id and $priority in the iteration, utilize for(key in obj) instead.
         */
        forEach: function(iterator, context) {
          return $firebaseUtils.each(this, iterator, context);
        }
      };

      /**
       * This method allows FirebaseObject to be copied into a new factory. Methods passed into this
       * function will be added onto the object's prototype. They can override existing methods as
       * well.
       *
       * In addition to passing additional methods, it is also possible to pass in a class function.
       * The prototype on that class function will be preserved, and it will inherit from
       * FirebaseObject. It's also possible to do both, passing a class to inherit and additional
       * methods to add onto the prototype.
       *
       * Once a factory is obtained by this method, it can be passed into $firebase as the
       * `objectFactory` parameter:
       *
       *

       * var MyFactory = $firebaseObject.$extend({
       *    // add a method onto the prototype that prints a greeting
       *    getGreeting: function() {
       *       return 'Hello ' + this.first_name + ' ' + this.last_name + '!';
       *    }
       * });
       *
       * // use our new factory in place of $firebaseObject
       * var obj = $firebase(ref, {objectFactory: MyFactory}).$asObject();
       *

       *
       * @param {Function} [ChildClass] a child class which should inherit FirebaseObject
       * @param {Object} [methods] a list of functions to add onto the prototype
       * @returns {Function} a new factory suitable for use with $firebase
       */
      FirebaseObject.$extend = function(ChildClass, methods) {
        if( arguments.length === 1 && angular.isObject(ChildClass) ) {
          methods = ChildClass;
          ChildClass = function(ref) {
            if( !(this instanceof ChildClass) ) {
              return new ChildClass(ref);
            }
            FirebaseObject.apply(this, arguments);
          };
        }
        return $firebaseUtils.inherit(ChildClass, FirebaseObject, methods);
      };

      /**
       * Creates a three-way data binding on a scope variable.
       *
       * @param {FirebaseObject} rec
       * @returns {*}
       * @constructor
       */
      function ThreeWayBinding(rec) {
        this.subs = [];
        this.scope = null;
        this.key = null;
        this.rec = rec;
      }

      ThreeWayBinding.prototype = {
        assertNotBound: function(varName) {
          if( this.scope ) {
            var msg = 'Cannot bind to ' + varName + ' because this instance is already bound to ' +
              this.key + '; one binding per instance ' +
              '(call unbind method or create another FirebaseObject instance)';
            $log.error(msg);
            return $q.reject(msg);
          }
        },

        bindTo: function(scope, varName) {
          function _bind(self) {
            var sending = false;
            var parsed = $parse(varName);
            var rec = self.rec;
            self.scope = scope;
            self.varName = varName;

            function equals(scopeValue) {
              return angular.equals(scopeValue, rec) &&
                scopeValue.$priority === rec.$priority &&
                scopeValue.$value === rec.$value;
            }

            function setScope(rec) {
              parsed.assign(scope, $firebaseUtils.scopeData(rec));
            }

            var send = $firebaseUtils.debounce(function(val) {
              var scopeData = $firebaseUtils.scopeData(val);
              rec.$$scopeUpdated(scopeData)
                ['finally'](function() {
                  sending = false;
                  if(!scopeData.hasOwnProperty('$value')){
                    delete rec.$value;
                    delete parsed(scope).$value;
                  }
                  setScope(rec);
                }
              );
            }, 50, 500);

            var scopeUpdated = function(newVal) {
              newVal = newVal[0];
              if( !equals(newVal) ) {
                sending = true;
                send(newVal);
              }
            };

            var recUpdated = function() {
              if( !sending && !equals(parsed(scope)) ) {
                setScope(rec);
              }
            };

            // $watch will not check any vars prefixed with $, so we
            // manually check $priority and $value using this method
            function watchExp(){
              var obj = parsed(scope);
              return [obj, obj.$priority, obj.$value];
            }

            setScope(rec);
            self.subs.push(scope.$on('$destroy', self.unbind.bind(self)));

            // monitor scope for any changes
            self.subs.push(scope.$watch(watchExp, scopeUpdated, true));

            // monitor the object for changes
            self.subs.push(rec.$watch(recUpdated));

            return self.unbind.bind(self);
          }

          return this.assertNotBound(varName) || _bind(this);
        },

        unbind: function() {
          if( this.scope ) {
            angular.forEach(this.subs, function(unbind) {
              unbind();
            });
            this.subs = [];
            this.scope = null;
            this.key = null;
          }
        },

        destroy: function() {
          this.unbind();
          this.rec = null;
        }
      };

      function ObjectSyncManager(firebaseObject, ref) {
        function destroy(err) {
          if( !sync.isDestroyed ) {
            sync.isDestroyed = true;
            ref.off('value', applyUpdate);
            firebaseObject = null;
            initComplete(err||'destroyed');
          }
        }

        function init() {
          ref.on('value', applyUpdate, error);
          ref.once('value', function(snap) {
            if (angular.isArray(snap.val())) {
              $log.warn('Storing data using array indices in Firebase can result in unexpected behavior. See https://firebase.google.com/docs/database/web/structure-data for more information. Also note that you probably wanted $firebaseArray and not $firebaseObject.');
            }

            initComplete(null);
          }, initComplete);
        }

        // call initComplete(); do not call this directly
        function _initComplete(err) {
          if( !isResolved ) {
            isResolved = true;
            if( err ) { def.reject(err); }
            else { def.resolve(firebaseObject); }
          }
        }

        var isResolved = false;
        var def = $q.defer();
        var applyUpdate = $firebaseUtils.batch(function(snap) {
          if (firebaseObject) {
            var changed = firebaseObject.$$updated(snap);
            if( changed ) {
              // notifies $watch listeners and
              // updates $scope if bound to a variable
              firebaseObject.$$notify();
            }
          }
        });
        var error = $firebaseUtils.batch(function(err) {
          _initComplete(err);
          if( firebaseObject ) {
            firebaseObject.$$error(err);
          }
        });
        var initComplete = $firebaseUtils.batch(_initComplete);

        var sync = {
          isDestroyed: false,
          destroy: destroy,
          init: init,
          ready: function() { return def.promise; }
        };
        return sync;
      }

      return FirebaseObject;
    }
  ]);

  /** @deprecated */
  angular.module('firebase').factory('$FirebaseObject', ['$log', '$firebaseObject',
    function($log, $firebaseObject) {
      return function() {
        $log.warn('$FirebaseObject has been renamed. Use $firebaseObject instead.');
        return $firebaseObject.apply(null, arguments);
      };
    }
  ]);
})();


text:
Clojure provides command line tools that can be used to start a Clojure repl, use Clojure and Java libraries, and start Clojure programs.

### Linux
Ensure that the following dependencies are installed: `bash`, `curl`, `rlwrap`, and `Java`.

```bash
curl -O https://download.clojure.org/install/linux-install-1.10.3.967.sh
chmod +x linux-install-1.10.3.967.sh
sudo ./linux-install-1.10.3.967.sh
```

### Homebrew for Mac OS X
Install the command line tools with brew from the [clojure/tools](https://github.com/clojure/homebrew-tools) tap:

```bash
brew install clojure/tools/clojure
```

### Windows
For running Clojure on Windows it is recommended to use WSL2.

Another way to install Clojure on Windows is with the [Scoop](https://scoop.sh/) package manager. To install scoop, open PowerShell and run these 2 commands, one after the other:

 ```sh
 iwr -useb get.scoop.sh | iex
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
``

To install Clojure with Scoop you have to add two important buckets first:

```sh
# if you don't have git version control system installed
# it is required for adding new external buckets to your scoop installer
# you can skip this step otherwise
scoop install git

# add scoop bucket for Java
scoop bucket add java

# add scoop bucket for clojure build
scoop bucket add scoop-clojure https://github.com/littleli/scoop-clojure
```

Now we are ready to install Java and Clojure by issuing following commands:

```sh
# install Java runtime and compiler
scoop install adoptopenjdk-lts-hotspot

# install official clojure tools
scoop install clojure

# update to the newest version
scoop update clojure
```

After successfully running steps above, you should be able to run Clojure with the following:

```sh
clj
```

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Print_ASCII_Table
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 33; i < 127; i++)
            {
                char symbol = (char)i;
                Console.Write(symbol);
            }
        }
    }
}


text:
using System.Collections.Generic;
using Orchard.ContentManagement.Records;
using Orchard.Data.Conventions;

namespace Orchard.Taxonomies.Models {
    public class TermsPartRecord : ContentPartRecord {
        public TermsPartRecord() {
            Terms = new List<TermContentItem>();
        }

        [CascadeAllDeleteOrphan]
        public virtual IList<TermContentItem> Terms { get; set; }
    }
}


text:
.class synthetic Landroid/support/v4/widget/ExploreByTouchHelper$1;
.super Ljava/lang/Object;
.source "ExploreByTouchHelper.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/widget/ExploreByTouchHelper;
.end annotation

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


text:
<?php

namespace GuzzleHttp\Tests\Http;

use GuzzleHttp\Stream\Stream;
use GuzzleHttp\Stream\LimitStream;

/**
 * @covers GuzzleHttp\Stream\LimitStream
 */
class LimitStreamTest extends \PHPUnit_Framework_TestCase
{
    /** @var LimitStream */
    protected $body;

    /** @var Stream */
    protected $decorated;

    public function setUp()
    {
        $this->decorated = Stream::factory(fopen(__FILE__, 'r'));
        $this->body = new LimitStream($this->decorated, 10, 3);
    }

    public function testReturnsSubset()
    {
        $body = new LimitStream(Stream::factory('foo'), -1, 1);
        $this->assertEquals('oo', (string) $body);
        $this->assertTrue($body->eof());
        $body->seek(0);
        $this->assertFalse($body->eof());
        $this->assertEquals('oo', $body->read(100));
        $this->assertTrue($body->eof());
    }

    public function testReturnsSubsetWhenCastToString()
    {
        $body = Stream::factory('foo_baz_bar');
        $limited = new LimitStream($body, 3, 4);
        $this->assertEquals('baz', (string) $limited);
    }

    public function testReturnsSubsetOfEmptyBodyWhenCastToString()
    {
        $body = Stream::factory('');
        $limited = new LimitStream($body, 0, 10);
        $this->assertEquals('', (string) $limited);
    }

    public function testSeeksWhenConstructed()
    {
        $this->assertEquals(0, $this->body->tell());
        $this->assertEquals(3, $this->decorated->tell());
    }

    public function testAllowsBoundedSeek()
    {
        $this->body->seek(100);
        $this->assertEquals(13, $this->decorated->tell());
        $this->body->seek(0);
        $this->assertEquals(0, $this->body->tell());
        $this->assertEquals(3, $this->decorated->tell());
        $this->assertEquals(false, $this->body->seek(1000, SEEK_END));
    }

    public function testReadsOnlySubsetOfData()
    {
        $data = $this->body->read(100);
        $this->assertEquals(10, strlen($data));
        $this->assertFalse($this->body->read(1000));

        $this->body->setOffset(10);
        $newData = $this->body->read(100);
        $this->assertEquals(10, strlen($newData));
        $this->assertNotSame($data, $newData);
    }

    public function testClaimsConsumedWhenReadLimitIsReached()
    {
        $this->assertFalse($this->body->eof());
        $this->body->read(1000);
        $this->assertTrue($this->body->eof());
    }

    public function testContentLengthIsBounded()
    {
        $this->assertEquals(10, $this->body->getSize());
    }

    public function testGetContentsIsBasedOnSubset()
    {
        $body = new LimitStream(Stream::factory('foobazbar'), 3, 3);
        $this->assertEquals('baz', $body->getContents());
    }
}


text:
PoC tool to compile a list of New Zealand Companies

 - filter by recently registered businesses
 - save company information into CSV file


text:
Black Pepper Support Spring Web MVC
===================================

Support for working with
[Spring Web MVC](http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html).

License
-------

* [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0.html)

[![Build Status](https://travis-ci.org/BlackPepperSoftware/bp-support-spring-webmvc.svg?branch=master)](https://travis-ci.org/BlackPepperSoftware/bp-support-spring-webmvc)


text:
require 'nrser/props/immutable/hash'

# Project / Package
# -----------------------------------------------------------------------

require_relative '../data'

# Definitions
# =======================================================================

# Abstract base class for immutable data classes. Based off {Hamster::Hash}.
#
# Using {Hamster::Hash}
#
module  QB
module  Data
class   Immutable < Hamster::Hash

  # Mixins
  # ========================================================================

  # Mark as a "data" class. Maybe will add some functionality at some point...
  include QB::Data

  # Infrastructure for a prop'd class based on {Hamster::Hash}
  include NRSER::Props::Immutable::Hash

end; end; end # class QB::Data::Immutable


text:
@class JYDickModel;

@interface JYPersonModel : NSObject
@property (nonatomic, strong) NSNumber *age;
@property NSArray *array;
@property NSString *str;
@end


text:
<XflowTest>
    <Input>

    	<data id="values" >
    		<float name="posKeys" >0  3  5</float>
    		<float3 name="positions" key="1" >0 0 -3   -4.5 3 0  -2 1 2</float3>

            <float name="rotKeys" >0  1  3</float>
            <float4 name="rotations" key="1" >
                0.156434 0.987688 0 0
                0.987688 0 0 0.156434
                0.587785 -0.467086 -0.467086 -0.467086
            </float4>
    	</data>

        <data id="posResult" compute="result = xflow.lerpKeys(posKeys, positions, key)">
            <data src="#values" />
            <float name="key" id="posKey" >0</float>
        </data>
        <data id="rotResult" compute="result = xflow.slerpKeys(rotKeys, rotations, key)">
            <data src="#values" />
            <float name="key" id="rotKey" >3</float>
        </data>

    </Input>
    <TestProcess>

        <Check title="Check Pos Lerp Result #1" data="#posResult" >
            <MatchData name="result" type="float3" >0 0 -3</MatchData>
        </Check>
        <Modification title="Change pos lerp key #1" >
            <ChangeData input="#posKey" >2</ChangeData>
        </Modification>
        <Check title="Check Pos Lerp Result #2" data="#posResult" >
            <MatchData name="result" type="float3" >-3 2 -1</MatchData>
        </Check>
        <Modification title="Change pos lerp key #2" >
            <ChangeData input="#posKey" >4</ChangeData>
        </Modification>
        <Check title="Check Pos Lerp Result #3" data="#posResult" >
            <MatchData name="result" type="float3" >-3.25 2 1</MatchData>
        </Check>
        <Modification title="Change pos lerp key #3" >
            <ChangeData input="#posKey" >9</ChangeData>
        </Modification>
        <Check title="Check Pos Lerp Result #4" data="#posResult" >
            <MatchData name="result" type="float3" >-2 1 2</MatchData>
        </Check>
        <Modification title="Change pos lerp key #4" >
            <ChangeData input="#posKey" >-1.33333</ChangeData>
        </Modification>
        <Check title="Check Pos Lerp Result #5" data="#posResult" >
            <MatchData name="result" type="float3" >0 0 -3</MatchData>
        </Check>

        <Check title="Check Rot Slerp Result #1" data="#rotResult" >
            <MatchData name="result" type="float4" >0.587785 -0.467086 -0.467086 -0.467086</MatchData>
        </Check>
        <Modification title="Change rot slerp key #1" >
            <ChangeData input="#rotKey">0.5</ChangeData>
        </Modification>
        <Check title="Check Rot Slerp Result #2" data="#rotResult" >
            <MatchData name="result" type="float4" >0.752938 0.64999 0 0.102948</MatchData>
        </Check>
        <Modification title="Change rot slerp key #1" >
            <ChangeData input="#rotKey">1.0</ChangeData>
        </Modification>
        <Check title="Check Rot Slerp Result #2" data="#rotResult" >
            <MatchData name="result" type="float4" >0.987688 0 0 0.156434</MatchData>
        </Check>
        <Modification title="Change rot slerp key #1" >
            <ChangeData input="#rotKey">0.8</ChangeData>
        </Modification>
        <Check title="Check Rot Slerp Result #2" data="#rotResult" >
            <MatchData name="result" type="float4" >0.949446 0.27928 0 0.143372</MatchData>
        </Check>
        <Modification title="Change rot slerp key #1" >
            <ChangeData input="#rotKey">1.4</ChangeData>
        </Modification>
        <Check title="Check Rot Slerp Result #2" data="#rotResult" >
            <MatchData name="result" type="float4" >0.987173 -0.111785 -0.111785 0.0222874</MatchData>
        </Check>

    </TestProcess>
</XflowTest>


text:
from patty.registration import get_stick_scale
from patty.registration.stickscale import get_confidence_level
from patty.segmentation import get_red_mask
from patty import load, extract_mask
from nose_parameterized import parameterized

from nose.tools import assert_greater, assert_less

from helpers import make_red_stick, _add_noise
import pcl
import numpy as np
import unittest

# The ground truths for these tests was defined by measuring stick segments,
# either white or red, by hand, in Meshlab.
# Note: failing instances commented out. Uncomment them for testing out
# new methods.
# @parameterized.expand([
# ("SITE9", 'redstick_SITE_9.ply', 11.45),
# ("SITE11", 'redstick_SITE_11.ply', 2.925),
# ("SITE12", 'redstick_SITE_12.ply', 10.85),

# only one segment visible
# ("SITE13", 'redstick_SITE_13.ply', 4.35),

# hardly anything of a segment is visible
# ("SITE14", 'redstick_SITE_14.ply', 1.07),

# ("SITE15", 'redstick_SITE_15.ply', 2.0),

# no red segments completely visible
# ("SITE16", 'redstick_SITE_16.ply', 5.13),

# one complete stick segment, one partly that contains more points (!)
# ("SITE19", 'redstick_SITE_19.ply', 3.15),

# ("SITE20", 'redstick_SITE_20.ply', 5.55),
# ("SITE21", 'redstick_SITE_21.ply', 5.4),
# ])

def make_pointcloud(sticks, noise):
    data = np.array(np.concatenate(sticks, axis=0), dtype=np.float32)
    _add_noise(data, noise, np.random.RandomState(0))
    pc = pcl.PointCloudXYZRGB(data)
    return extract_mask(pc, get_red_mask(pc))

@parameterized.expand([(0.01,), (0.02,), (0.05,), (0.1,)])
def test_stickscale(noise):
    s1 = make_red_stick([0, 0, 0], [0, 1, 0])
    s2 = make_red_stick([1, 2, 0], [1, 1, 0])
    s3 = make_red_stick([3, 3, 0], [3, 4, 0])
    pc = make_pointcloud((s1, s2, s3), noise)
    meter, confidence = get_stick_scale(pc)
    red_part_length = 0.25 + noise
    assert_with_error(meter, 4 * red_part_length / 0.8)
    assert_with_error(confidence, 1.0)

@parameterized.expand([
    (500, 3, 1.0),
    (100, 3, 1.0 / 5.0),
    (500, 2, 2.0 / 3.0),
    (500, 1, 1.0 / 3.0),
    (100, 2, min(1.0 / 5.0, 2.0 / 3.0)),
])
def test_confidence(votes, numberOfClusters, expected_confidence):
    confidence = get_confidence_level(votes, numberOfClusters)
    assert_with_error(confidence, expected_confidence)

# The ground truths for these tests was defined by measuring stick segments,
# either white or red, by hand, in Meshlab. """
@parameterized.expand([
    # ("SITE9", 'redstick_SITE_9.ply', 11.45, True),
    # ("SITE11", 'redstick_SITE_11.ply', 2.925, True),
    # ("SITE12", 'redstick_SITE_12.ply', 10.85, True),
    # ("SITE13", 'redstick_SITE_13.ply', 4.35, False),
    # # only one segment visible
    # ("SITE14", 'redstick_SITE_14.ply', 1.07, False),
    # # hardly anything of a segment is visible
    # ("SITE15", 'redstick_SITE_15.ply', 2.0, True),
    # ("SITE16", 'redstick_SITE_16.ply', 5.13, False),
    # # no red segments completely visible
    # ("SITE19", 'redstick_SITE_19.ply', 3.15, False),
    # # one complete stick segment, and one partly that contains more points
    # # (!)
    # ("SITE20", 'redstick_SITE_20.ply', 5.55, True),
    # ("SITE21", 'redstick_SITE_21.ply', 5.4, True)
])
def test_actual_data_confidence(name, filename, expected_meter,
                                expect_confident):
    pc = load('tests/testdata/' + filename)
    meter, confidence = get_stick_scale(pc)
    if expect_confident:
        assert_greater(confidence, .5, "confidence too low")
    else:
        assert_less(confidence, .5, "confidence too high")

def assert_with_error(estimated, expected):
    error_ratio = 0.05
    margin = error_ratio * expected
    message = ('Value does not match expected value with %f%% (%f) margin.'
               '\nEstimated: %f\nExpected: %f' % (100 * error_ratio,
                                                  margin, estimated, expected))
    assert_less(abs(estimated - expected), margin, message)

class TestStickScale(unittest.TestCase):

    def test_stickscale_emptycloud(noise):
        '''Cloud with zero point should return zero confidence.'''
        pc = pcl.PointCloudXYZRGB()
        meter, confidence = get_stick_scale(pc)
        np.testing.assert_almost_equal(confidence, 0.0)

    def test_stickscale_nocluster(noise):
        '''Cloud without clusters should return zero confidence.'''
        pc = pcl.PointCloudXYZRGB([[0, 0, 0], [10000, 10000, 10000]])
        meter, confidence = get_stick_scale(pc)
        np.testing.assert_almost_equal(confidence, 0.0)


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

<access component="com_citations">

		<action name="core.admin" title="JACTION_ADMIN" description="JACTION_ADMIN_COMPONENT_DESC" />
		<action name="core.manage" title="JACTION_MANAGE" description="JACTION_MANAGE_COMPONENT_DESC" />
		<action name="core.create" title="JACTION_CREATE" description="JACTION_CREATE_COMPONENT_DESC" />
		<action name="core.delete" title="JACTION_DELETE" description="JACTION_DELETE_COMPONENT_DESC" />
		<action name="core.edit" title="JACTION_EDIT" description="JACTION_EDIT_COMPONENT_DESC" />
		<action name="core.edit.state" title="JACTION_EDITSTATE" description="JACTION_EDITSTATE_COMPONENT_DESC" />
		<action name="core.edit.own" title="JACTION_EDITOWN" description="JACTION_EDITOWN_COMPONENT_DESC" />

		<action name="core.create" title="JACTION_CREATE" description="COM_CITATIONS_ACCESS_CREATE_DESC" />
		<action name="core.delete" title="JACTION_DELETE" description="COM_CITATIONS_ACCESS_DELETE_DESC" />
		<action name="core.edit" title="JACTION_EDIT" description="COM_CITATIONS_ACCESS_EDIT_DESC" />
		<action name="core.edit.state" title="JACTION_EDITSTATE" description="COM_CITATIONS_ACCESS_EDITSTATE_DESC" />
		<action name="core.edit.own" title="JACTION_EDITOWN" description="COM_CITATIONS_ACCESS_EDITOWN_DESC" />

		<action name="core.create" title="JACTION_CREATE" description="COM_CITATIONS_ACCESS_CREATE_DESC" />
		<action name="core.delete" title="JACTION_DELETE" description="COM_CITATIONS_ACCESS_DELETE_DESC" />
		<action name="core.edit" title="JACTION_EDIT" description="COM_CITATIONS_ACCESS_EDIT_DESC" />
		<action name="core.edit.state" title="JACTION_EDITSTATE" description="COM_CITATIONS_ACCESS_EDITSTATE_DESC" />
		<action name="core.edit.own" title="JACTION_EDITOWN" description="COM_CITATIONS_ACCESS_EDITOWN_DESC" />

		<action name="core.create" title="JACTION_CREATE" description="COM_CITATIONS_ACCESS_CREATE_DESC" />
		<action name="core.delete" title="JACTION_DELETE" description="COM_CITATIONS_ACCESS_DELETE_DESC" />
		<action name="core.edit" title="JACTION_EDIT" description="COM_CITATIONS_ACCESS_EDIT_DESC" />
		<action name="core.edit.state" title="JACTION_EDITSTATE" description="COM_CITATIONS_ACCESS_EDITSTATE_DESC" />
		<action name="core.edit.own" title="JACTION_EDITOWN" description="COM_CITATIONS_ACCESS_EDITOWN_DESC" />

</access>


text:
/* VideoDecoderCapabilities implementation */

#include "sles_allinclusive.h"
#ifdef ANDROID
#include "android/VideoCodec_to_android.h"
#endif

static XAresult IVideoDecoderCapabilities_GetVideoDecoders(XAVideoDecoderCapabilitiesItf self,
    XAuint32 *pNumDecoders, XAuint32 *pDecoderIds)
{
    XA_ENTER_INTERFACE

    if (NULL == pNumDecoders) {
        result = XA_RESULT_PARAMETER_INVALID;
    } else {
        if (NULL == pDecoderIds) {
            // If pDecoderIds is NULL, pNumDecoders returns the number of decoders available.
#ifdef ANDROID
            *pNumDecoders = android::android_videoCodec_getNbDecoders();
#else
            *pNumDecoders = kMaxVideoDecoders;
#endif

        } else {
            // If pDecodersIds is non-NULL, as an input pNumDecoders specifies the size of the
            // pDecoderIds array and as an output it specifies the number of decoder IDs available
            // within the pDecoderIds array.
            XAuint32 numDecoders = *pNumDecoders;
#ifdef ANDROID
            const XAuint32 androidNbDecoders = android::android_videoCodec_getNbDecoders();
            if (androidNbDecoders < numDecoders) {
                *pNumDecoders = numDecoders = androidNbDecoders;
            }
            android::android_videoCodec_getDecoderIds(numDecoders, pDecoderIds);
#else
            if (kMaxVideoDecoders < numDecoders) {
                *pNumDecoders = numDecoders = kMaxVideoDecoders;
            }
            memcpy(pDecoderIds, VideoDecoderIds, numDecoders * sizeof(XAuint32));
#endif
        }
        result = XA_RESULT_SUCCESS;
    }

    XA_LEAVE_INTERFACE
}

static XAresult IVideoDecoderCapabilities_GetVideoDecoderCapabilities(
    XAVideoDecoderCapabilitiesItf self, XAuint32 decoderId, XAuint32 *pIndex,
    XAVideoCodecDescriptor *pDescriptor)
{
    XA_ENTER_INTERFACE

    if (NULL == pIndex) {
        result = XA_RESULT_PARAMETER_INVALID;
    } else {
        if (NULL == pDescriptor) {
            // pIndex returns the number of video decoders capability descriptions.
#ifdef ANDROID
            result = android::android_videoCodec_getProfileLevelCombinationNb(decoderId, pIndex);
#else
            // Generic implementation has zero profile/level combinations for all codecs,
            // but this is not allowed per spec:
            //    "Each decoder must support at least one profile/mode pair
            //    and therefore have at least one Codec Descriptor."
            *pIndex = 0;
            SL_LOGE("Generic implementation has no video decoder capabilities");
            result = XA_RESULT_PARAMETER_INVALID;
#endif
        } else {
            // pIndex is an incrementing value used to enumerate capability descriptions.
#ifdef ANDROID
            result = android::android_videoCodec_getProfileLevelCombination(decoderId, *pIndex,
                    pDescriptor);
#else
            // For the generic implementation, any index >= 0 is out of range
#if 1   // not sure if this is needed, it's not being done for the Android case
            pDescriptor->codecId = decoderId;
#endif
            SL_LOGE("Generic implementation has no video decoder capabilities");
            result = XA_RESULT_PARAMETER_INVALID;
#endif
        }
    }

    XA_LEAVE_INTERFACE
}

static const struct XAVideoDecoderCapabilitiesItf_ IVideoDecoderCapabilities_Itf = {
    IVideoDecoderCapabilities_GetVideoDecoders,
    IVideoDecoderCapabilities_GetVideoDecoderCapabilities
};

void IVideoDecoderCapabilities_init(void *self)
{
    IVideoDecoderCapabilities *thiz = (IVideoDecoderCapabilities *) self;
    thiz->mItf = &IVideoDecoderCapabilities_Itf;
}

bool IVideoDecoderCapabilities_expose(void *self)
{
#ifdef ANDROID
    // This is an Engine object interface, so we allocate the associated resources every time
    //   the interface is exposed on the Engine object and free them when the object is about
    //   to be destroyed (see IVideoDecoderCapabilities_deinit), not just once during the
    //   lifetime of the process.
    return android::android_videoCodec_expose();
#else
    return false;
#endif
}

void IVideoDecoderCapabilities_deinit(void *self)
{
    SL_LOGV("IVideoDecoderCapabilities_deinit()");
#ifdef ANDROID
    android::android_videoCodec_deinit();
#endif
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>sbml2matlab: NameValue Class Reference</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

<link href="search/search.css" rel="stylesheet" type="text/css"/>

sbml2matlab
    1.02

SBML to MATLAB translator

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Members

 All Classes Files Functions

Public Attributes

NameValue Class Reference

List of all members.

Public Attributes

string 	name

double 	value

The documentation for this class was generated from the following file:

sbml2matlab.cpp

<address class="footer">
Generated on Fri Mar 30 2012 13:04:01 for sbml2matlab by

 1.8.0
</address>


text:
def test
  connection = Fog::Compute.new({ :provider => "Google" })

  name = "fog-smoke-test-#{Time.now.to_i}"

  disk = connection.disks.create({
    :name => name,
    :size_gb => 10,
    :zone_name => 'us-central1-a',
    :source_image => 'debian-7-wheezy-v20131120',
  })

  disk.wait_for { disk.ready? }

  server = connection.servers.create({
    :name => name,
    :disks => [disk],
    :machine_type => "n1-standard-1",
    :zone_name => "us-central1-a",
    :private_key_path => File.expand_path("~/.ssh/id_rsa"),
    :public_key_path => File.expand_path("~/.ssh/id_rsa.pub"),
    :username => 'root',
    :metadata => {'foo' => 'bar'}
  })
  sleep(90)

  raise "Could not reload created server." unless server.reload
  raise "Could not create sshable server." unless server.ssh("whoami")
  raise "Could not delete server." unless server.destroy
end


text:
import sys
import argparse
import json

from config import DPI, WIDTH, HEIGHT
import svg

# Generates an SVG from a JSON clock description.
def main():
    parser = argparse.ArgumentParser(description='Generate gears.')
    parser.add_argument("input", help="JSON filename to read")
    args = parser.parse_args()

    data = json.load(open(args.input))
    pieces = data["pieces"]

    out = sys.stdout
    x_multiplier = 1.0
    cz_vertical_offset = 5*DPI*0

    svg.header(out, WIDTH*x_multiplier, HEIGHT*7)

    # Make cuts.
    for piece_index, piece in enumerate(data["pieces"]):
        cx = piece["cx"]*x_multiplier
        cy = piece["cy"] + piece["cz"]*cz_vertical_offset
        color = piece["color"]

        # Always use black for cut, it makes it easier to see in AI.
        color = "black"

        name = "%s_%d" % (piece["type"], piece_index)
        svg.start_group(out, name, cx, cy)

        p = piece["points"]
        svg.start_group(out, name + "_body")
        svg.polyline(out, p, color)
        svg.end_group(out)

        if "hole_radius" in piece:
            svg.start_group(out, name + "_hole")
            svg.circle(out, 0, 0, piece["hole_radius"], color)
            svg.end_group(out)
        if "bind" in piece:
            bind = piece["bind"]
            bind_radius = bind["hole_radius"]
            svg.start_group(out, name + "_bind")
            for center in bind["centers"]:
                svg.circle(out, center[0], center[1], bind_radius, color)
            svg.end_group(out)
        if "holes" in piece:
            # Also cut holes from all the axles.
            svg.start_group(out, name + "_holes")
            for hole in piece["holes"]:
                svg.circle(out, hole["cx"], hole["cy"], hole["r"], color)
            svg.end_group(out)

        svg.end_group(out)

    svg.footer(out)

if __name__ == "__main__":
    main()


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.
 *
 *****************************************************************************
 *
 *  \file   event.h
 *
 *  \brief  Events!
 *
 *  \version
 *      - S Panyam      18/02/2009
 *        Created
 *
 *****************************************************************************/

#ifndef _SEVENT_H_
#define _SEVENT_H_

#include "eds/fwd.h"

//*****************************************************************************
/*!
 *  \class  Holds all info for an event.
 *
 *  \brief  An event queue used by event handlers and dispatchers.
 *
 *****************************************************************************/
class SEvent
{
public:
    //! Creates a new event with defaults
    SEvent(int type = -1, SJob *pSource = NULL, void *data = NULL, int priority_ = 1000)
    {
        Reset(type, pSource, data, priority_);
    }

    //! Reset the event.
    void Reset(int type = -1, SJob *pSource_ = NULL, void *data = NULL, int priority_ = 1000)
    {
        // default priority = 1000
        priority    = priority_;
        evType      = type;
        pSource     = pSource_;
        pData       = data;
    }

    //! Return the extra data.
    template <typename T> T Data() const { return reinterpret_cast<T>(pData); }

    //! event type - app specific
    int     evType;

    //! The source that is responsible for this event.
    SJob *  pSource;

    //! The actual event data - can be a bucket, string, anything really -
    // specific to the module and event type
    void *  pData;

    //! Priority of the event
    int     priority;
};

// overloaded to do comparison between 2 events
extern bool operator<(const SEvent &a, const SEvent &b);

#endif


text:
<?php

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolesTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Role::create(['name' => 'Superuser']);
        Role::create(['name' => 'Admin']);
        Role::create(['name' => 'Standard user']);

        Permission::create(['name' => 'Superuser Right']);
        Permission::create(['name' => 'Administration Right']);
        Permission::create(['name' => 'View Right']);
        Permission::create(['name' => 'Comment Right']);
        Permission::create(['name' => 'Edit Right']);
        Permission::create(['name' => 'Delete Right']);
    }
}


text:
The dotnet repository is the starting point to engage in and learn about .NET
open source projects from [Microsoft](http://microsoft.github.io) and the
[.NET Foundation](http://www.dotnetfoundation.org/). You can read the more detailed post
[.NET Core is Open Source](http://blogs.msdn.com/b/dotnet/archive/2014/11/12/net-core-is-open-source.aspx)
on the .NET blog.

## Finding .NET Open Source Projects

There are many [open source .NET projects](dotnet-developer-projects.md), a few of which are listed below. Additionally [@quozd](https://github.com/quozd) maintains a list of [awesome open source .NET libraries, tools, frameworks, and software](https://github.com/quozd/awesome-dotnet).

* [.NET Compiler Platform ("Roslyn")](https://github.com/dotnet/roslyn)
* [.NET Core](https://github.com/dotnet/core)
* [ASP.NET 5](https://github.com/aspnet/home)
* [EntityFramework](https://github.com/aspnet/EntityFramework)
* [Exceptionless](https://github.com/exceptionless/Exceptionless)
* [Glimpse](http://getglimpse.com)
* [JSON.NET](http://json.net/)
* [MonoGame](http://monogame.net)
* [Mono Project](https://github.com/mono/)
* [MVVM Cross](https://github.com/MvvmCross/MvvmCross)
* [MVVM Light Toolkit](http://www.mvvmlight.net)
* [ReactiveUI](https://github.com/reactiveui/ReactiveUI)

For a longer list, see:

* [.NET developer projects](dotnet-developer-projects.md)
* [.NET consumer projects](dotnet-consumer-projects.md)

For a list of free services and tools for open source .NET projects, see:

* [Free Services & Tools for Open Source .NET Projects](dotnet-free-oss-services.md)

## How to Engage, Contribute and Provide Feedback

.NET open source projects from Microsoft (gladly) accept PRs and other
contributions. To contribute to ASP.NET 5 or EntityFramework, see
[the ASP.NET Contributing Guide](https://github.com/aspnet/Home/blob/master/CONTRIBUTING.md).
To contribute to .NET Core, see the
[.NET Core Contributing Guide](https://github.com/dotnet/corefx/wiki/Contributing).

You are also encouraged to start a discussion by posting on the
[.NET Foundation Forums](http://forums.dotnetfoundation.org/) or filing an issue
in the corresponding GitHub project. See the contributing guides for more
details.

## .NET Foundation

Most .NET open source projects at Microsoft have been contributed to the
[.NET Foundation](http://www.dotnetfoundation.org/projects). There are two main
.NET Foundation projects for Microsoft open source projects:
[ASP.NET Core 5 project](http://www.dotnetfoundation.org/aspnet-5)
and the [.NET Core project](http://www.dotnetfoundation.org/netcore).

## License

.NET open source projects typically use either the [MIT](LICENSE) or
[Apache 2](http://www.apache.org/licenses/LICENSE-2.0) licenses for code. Some
projects license documentation and other forms of content under
[Creative Commons Attribution 4.0](http://creativecommons.org/licenses/by/4.0/).
See specific projects to understand the license used.


text:
from __future__ import annotations

import logging
import logging.config
import os
import re

from airflow.config_templates.airflow_local_settings import DEFAULT_LOGGING_CONFIG
from airflow.models import DAG, DagRun, TaskInstance
from airflow.operators.python import PythonOperator
from airflow.utils.log.file_task_handler import FileTaskHandler
from airflow.utils.log.logging_mixin import set_context
from airflow.utils.session import create_session
from airflow.utils.state import State
from airflow.utils.timezone import datetime
from airflow.utils.types import DagRunType

DEFAULT_DATE = datetime(2016, 1, 1)
TASK_LOGGER = 'airflow.task'
FILE_TASK_HANDLER = 'task'

class TestFileTaskLogHandler:
    def clean_up(self):
        with create_session() as session:
            session.query(DagRun).delete()
            session.query(TaskInstance).delete()

    def setup_method(self):
        logging.config.dictConfig(DEFAULT_LOGGING_CONFIG)
        logging.root.disabled = False
        self.clean_up()
        # We use file task handler by default.

    def teardown_method(self):
        self.clean_up()

    def test_default_task_logging_setup(self):
        # file task handler is used by default.
        logger = logging.getLogger(TASK_LOGGER)
        handlers = logger.handlers
        assert len(handlers) == 1
        handler = handlers[0]
        assert handler.name == FILE_TASK_HANDLER

    def test_file_task_handler_when_ti_value_is_invalid(self):
        def task_callable(ti):
            ti.log.info("test")

        dag = DAG('dag_for_testing_file_task_handler', start_date=DEFAULT_DATE)
        dagrun = dag.create_dagrun(
            run_type=DagRunType.MANUAL,
            state=State.RUNNING,
            execution_date=DEFAULT_DATE,
        )
        task = PythonOperator(
            task_id='task_for_testing_file_log_handler',
            dag=dag,
            python_callable=task_callable,
        )
        ti = TaskInstance(task=task, run_id=dagrun.run_id)

        logger = ti.log
        ti.log.disabled = False

        file_handler = next(
            (handler for handler in logger.handlers if handler.name == FILE_TASK_HANDLER), None
        )
        assert file_handler is not None

        set_context(logger, ti)
        assert file_handler.handler is not None
        # We expect set_context generates a file locally.
        log_filename = file_handler.handler.baseFilename
        assert os.path.isfile(log_filename)
        assert log_filename.endswith("1.log"), log_filename

        ti.run(ignore_ti_state=True)

        file_handler.flush()
        file_handler.close()

        assert hasattr(file_handler, 'read')
        # Return value of read must be a tuple of list and list.
        # passing invalid `try_number` to read function
        logs, metadatas = file_handler.read(ti, 0)
        assert isinstance(logs, list)
        assert isinstance(metadatas, list)
        assert len(logs) == 1
        assert len(logs) == len(metadatas)
        assert isinstance(metadatas[0], dict)
        assert logs[0][0][0] == "default_host"
        assert logs[0][0][1] == "Error fetching the logs. Try number 0 is invalid."

        # Remove the generated tmp log file.
        os.remove(log_filename)

    def test_file_task_handler(self):
        def task_callable(ti):
            ti.log.info("test")

        dag = DAG('dag_for_testing_file_task_handler', start_date=DEFAULT_DATE)
        dagrun = dag.create_dagrun(
            run_type=DagRunType.MANUAL,
            state=State.RUNNING,
            execution_date=DEFAULT_DATE,
        )
        task = PythonOperator(
            task_id='task_for_testing_file_log_handler',
            dag=dag,
            python_callable=task_callable,
        )
        ti = TaskInstance(task=task, run_id=dagrun.run_id)

        logger = ti.log
        ti.log.disabled = False

        file_handler = next(
            (handler for handler in logger.handlers if handler.name == FILE_TASK_HANDLER), None
        )
        assert file_handler is not None

        set_context(logger, ti)
        assert file_handler.handler is not None
        # We expect set_context generates a file locally.
        log_filename = file_handler.handler.baseFilename
        assert os.path.isfile(log_filename)
        assert log_filename.endswith("1.log"), log_filename

        ti.run(ignore_ti_state=True)

        file_handler.flush()
        file_handler.close()

        assert hasattr(file_handler, 'read')
        # Return value of read must be a tuple of list and list.
        logs, metadatas = file_handler.read(ti)
        assert isinstance(logs, list)
        assert isinstance(metadatas, list)
        assert len(logs) == 1
        assert len(logs) == len(metadatas)
        assert isinstance(metadatas[0], dict)
        target_re = r'\n\[[^\]]+\] {test_log_handlers.py:\d+} INFO - test\n'

        # We should expect our log line from the callable above to appear in
        # the logs we read back
        assert re.search(target_re, logs[0][0][-1]), "Logs were " + str(logs)

        # Remove the generated tmp log file.
        os.remove(log_filename)

    def test_file_task_handler_running(self):
        def task_callable(ti):
            ti.log.info("test")

        dag = DAG('dag_for_testing_file_task_handler', start_date=DEFAULT_DATE)
        task = PythonOperator(
            task_id='task_for_testing_file_log_handler',
            python_callable=task_callable,
            dag=dag,
        )
        dagrun = dag.create_dagrun(
            run_type=DagRunType.MANUAL,
            state=State.RUNNING,
            execution_date=DEFAULT_DATE,
        )
        ti = TaskInstance(task=task, run_id=dagrun.run_id)

        ti.try_number = 2
        ti.state = State.RUNNING

        logger = ti.log
        ti.log.disabled = False

        file_handler = next(
            (handler for handler in logger.handlers if handler.name == FILE_TASK_HANDLER), None
        )
        assert file_handler is not None

        set_context(logger, ti)
        assert file_handler.handler is not None
        # We expect set_context generates a file locally.
        log_filename = file_handler.handler.baseFilename
        assert os.path.isfile(log_filename)
        assert log_filename.endswith("2.log"), log_filename

        logger.info("Test")

        # Return value of read must be a tuple of list and list.
        logs, metadatas = file_handler.read(ti)
        assert isinstance(logs, list)
        # Logs for running tasks should show up too.
        assert isinstance(logs, list)
        assert isinstance(metadatas, list)
        assert len(logs) == 2
        assert len(logs) == len(metadatas)
        assert isinstance(metadatas[0], dict)

        # Remove the generated tmp log file.
        os.remove(log_filename)

class TestFilenameRendering:
    def test_python_formatting(self, create_log_template, create_task_instance):
        create_log_template("{dag_id}/{task_id}/{execution_date}/{try_number}.log")
        filename_rendering_ti = create_task_instance(
            dag_id="dag_for_testing_filename_rendering",
            task_id="task_for_testing_filename_rendering",
            run_type=DagRunType.SCHEDULED,
            execution_date=DEFAULT_DATE,
        )

        expected_filename = (
            f"dag_for_testing_filename_rendering/task_for_testing_filename_rendering/"
            f"{DEFAULT_DATE.isoformat()}/42.log"
        )
        fth = FileTaskHandler("")
        rendered_filename = fth._render_filename(filename_rendering_ti, 42)
        assert expected_filename == rendered_filename

    def test_jinja_rendering(self, create_log_template, create_task_instance):
        create_log_template("{{ ti.dag_id }}/{{ ti.task_id }}/{{ ts }}/{{ try_number }}.log")
        filename_rendering_ti = create_task_instance(
            dag_id="dag_for_testing_filename_rendering",
            task_id="task_for_testing_filename_rendering",
            run_type=DagRunType.SCHEDULED,
            execution_date=DEFAULT_DATE,
        )

        expected_filename = (
            f"dag_for_testing_filename_rendering/task_for_testing_filename_rendering/"
            f"{DEFAULT_DATE.isoformat()}/42.log"
        )
        fth = FileTaskHandler("")
        rendered_filename = fth._render_filename(filename_rendering_ti, 42)
        assert expected_filename == rendered_filename


text:
layout: default
permalink: validation/errors
title: Errors
---

# Introduction

The validator returns detailed errors for each validation failure.  Calling the `errors` method on the validator will return an array of [ValidationError objects](https://github.com/thephpleague/json-guard/blob/master/src/ValidationError.php).  Since the ValidationError objects can be serialized as JSON, if you serialized them they would look something like this:

```json
[
    {
        "message": "Value 1234 is not a(n) \"string\"",
        "keyword": "type",
        "parameter": "string",
        "data": 1234,
        "data_path": "/name",
        "schema": {
            "description": "Name of the product",
            "type": "string"
        },
        "schema_path": "/properties/name/type",
        "cause": 1234
    },
    {
        "message": "Value 2 is not a(n) \"string\"",
        "keyword": "type",
        "parameter": "string",
        "data": 2,
        "data_path": "/sub-product/sub-product/tags/1",
        "schema": {
            "type": "string"
        },
        "schema_path": "/properties/sub-product/properties/sub-product/properties/tags/items/1/type",
        "cause": 2
    }
]
```

## Error Format

### Message

The message is a developer friendly explanation of what caused the error.

The `message` is intended for developers and is not localized.  Error messages can be easily localized for your application using the keyword, the context, and the [symfony/translation](http://symfony.com/doc/current/components/translation/usage.html) component or a similar library.

### Keyword

The keyword is a unique identifier for this error type.  The keyword is the property name used in the schema.  You can view the complete list of keywords [here](http://json-schema.org/latest/json-schema-validation.html#rfc.section.5).

### Parameter

The parameter passed to the constraint.  For the schema `{"type": "string"}`, the parameter would be "string".

### Data

The data that caused the error.

### Data Path

The data path is a [JSON Pointer](https://tools.ietf.org/html/rfc6901) to the data that caused the error.

### Schema

The schema the data failed to validate against.  If the error was thrown by a nested schema this will only contain the nested schema.

### Schema Path

The schema path is a [JSON Pointer](https://tools.ietf.org/html/rfc6901) to the schema the data failed to validate against.

### Cause

The cause of the failed validation.  In most cases this is the data.  This may be a subset of the data that caused validation to fail (i.e. the additional properties that caused additionalProperties to fail) or missing data that was expected (i.e. the missing dependency that caused dependencies to fail).

### Context

The context array holds any data meant to be interpolated into the error message.  For example, the schema `{"minimum": 2}` and the data `1` would return this context:

```
{
    "keyword": "minimum",
    "parameter": "2",
    "data": "1",
    "data_path": "/",
    "schema": "{\"minimum\":2}",
    "schema_path": "/minimum",
    "cause": "1"
}
```

Every value in the array is cast to a string so that it can be safely interpolated and truncated if over 100 characters long.


text:
"""
    SoftLayer.tests.CLI.modules.block_tests
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    :license: MIT, see LICENSE for more details.
"""
from SoftLayer import testing

import json
import mock

class BlockTests(testing.TestCase):

    def test_access_list(self):
        result = self.run_command(['block', 'access-list', '1234'])

        self.assert_no_fail(result)
        self.assertEqual([
            {
                'username': 'joe',
                'name': 'test-server.example.com',
                'type': 'VIRTUAL',
                'host_iqn': 'test-server',
                'password': '12345',
                'private_ip_address': '10.0.0.1',
                'id': 1234,
            },
            {
                'username': 'joe',
                'name': 'test-server.example.com',
                'type': 'HARDWARE',
                'host_iqn': 'test-server',
                'password': '12345',
                'private_ip_address': '10.0.0.2',
                'id': 1234,
            },
            {
                'username': 'joe',
                'name': '10.0.0.1/24 (backend subnet)',
                'type': 'SUBNET',
                'host_iqn': 'test-server',
                'password': '12345',
                'private_ip_address': None,
                'id': 1234,
            },
            {
                'username': 'joe',
                'name': '10.0.0.1 (backend ip)',
                'type': 'IP',
                'host_iqn': 'test-server',
                'password': '12345',
                'private_ip_address': None,
                'id': 1234,
            }],
            json.loads(result.output),)

    def test_volume_cancel(self):
        result = self.run_command([
            '--really', 'block', 'volume-cancel', '1234'])

        self.assert_no_fail(result)
        self.assertEqual('Block volume with id 1234 has been marked'
                         ' for cancellation\n', result.output)
        self.assert_called_with('SoftLayer_Billing_Item', 'cancelItem',
                                args=(False, True, None))

    def test_volume_detail(self):
        result = self.run_command(['block', 'volume-detail', '1234'])
        self.assert_no_fail(result)
        self.assertEqual({
            'Username': 'username',
            'LUN Id': '2',
            'Endurance Tier': '2 IOPS per GB',
            'IOPs': 1000,
            'Snapshot Capacity (GB)': '10',
            'Snapshot Used (Bytes)': 1024,
            'Capacity (GB)': '20GB',
            'Target IP': '10.1.2.3',
            'Data Center': 'dal05',
            'Type': 'ENDURANCE',
            'ID': 100,
            '# of Active Transactions': '0',
            'Replicant Count': '1',
            'Replication Status': 'Replicant Volume Provisioning '
                                  'has completed.',
            'Replicant Volumes': [[
                {'Replicant ID': 'Volume Name', '1784': 'TEST_REP_1'},
                {'Replicant ID': 'Target IP', '1784': '10.3.174.79'},
                {'Replicant ID': 'Data Center', '1784': 'wdc01'},
                {'Replicant ID': 'Schedule', '1784': 'REPLICATION_HOURLY'},
            ], [
                {'Replicant ID': 'Volume Name', '1785': 'TEST_REP_2'},
                {'Replicant ID': 'Target IP', '1785': '10.3.177.84'},
                {'Replicant ID': 'Data Center', '1785': 'dal01'},
                {'Replicant ID': 'Schedule', '1785': 'REPLICATION_DAILY'},
            ]]
        }, json.loads(result.output))

    def test_volume_list(self):
        result = self.run_command(['block', 'volume-list'])

        self.assert_no_fail(result)
        self.assertEqual([
            {
                'bytes_used': None,
                'capacity_gb': 20,
                'datacenter': None,
                'id': 100,
                'ip_addr': '10.1.2.3',
                'lunId': None,
                'storage_type': 'ENDURANCE',
                'username': 'username',
                'active_transactions': None
            }],
            json.loads(result.output))

    def test_volume_order_performance_iops_not_given(self):
        result = self.run_command(['block', 'volume-order',
                                   '--storage-type=performance', '--size=20',
                                   '--os-type=linux', '--location=dal05'])

        self.assertEqual(2, result.exit_code)

    def test_volume_order_performance_iops_out_of_range(self):
        result = self.run_command(['block', 'volume-order',
                                   '--storage-type=performance', '--size=20',
                                   '--iops=80000', '--os-type=linux',
                                   '--location=dal05'])

        self.assertEqual(2, result.exit_code)

    def test_volume_order_performance_iops_not_multiple_of_100(self):
        result = self.run_command(['block', 'volume-order',
                                   '--storage-type=performance', '--size=20',
                                   '--iops=122', '--os-type=linux',
                                   '--location=dal05'])

        self.assertEqual(2, result.exit_code)

    def test_volume_order_performance_snapshot_error(self):
        result = self.run_command(['block', 'volume-order',
                                   '--storage-type=performance', '--size=20',
                                   '--iops=100', '--os-type=linux',
                                   '--location=dal05', '--snapshot-size=10'])

        self.assertEqual(2, result.exit_code)

    @mock.patch('SoftLayer.BlockStorageManager.order_block_volume')
    def test_volume_order_performance(self, order_mock):
        order_mock.return_value = {
            'placedOrder': {
                'id': 478,
                'items': [
                    {'description': 'Performance Storage'},
                    {'description': 'Block Storage'},
                    {'description': '0.25 IOPS per GB'},
                    {'description': '20 GB Storage Space'}]
            }
        }

        result = self.run_command(['block', 'volume-order',
                                   '--storage-type=performance', '--size=20',
                                   '--iops=100', '--os-type=linux',
                                   '--location=dal05'])

        self.assert_no_fail(result)
        self.assertEqual(result.output,
                         'Order #478 placed successfully!\n'
                         ' > Performance Storage\n > Block Storage\n'
                         ' > 0.25 IOPS per GB\n > 20 GB Storage Space\n')

    def test_volume_order_endurance_tier_not_given(self):
        result = self.run_command(['block', 'volume-order',
                                   '--storage-type=endurance', '--size=20',
                                   '--os-type=linux', '--location=dal05'])

        self.assertEqual(2, result.exit_code)

    @mock.patch('SoftLayer.BlockStorageManager.order_block_volume')
    def test_volume_order_endurance(self, order_mock):
        order_mock.return_value = {
            'placedOrder': {
                'id': 478,
                'items': [
                    {'description': 'Endurance Storage'},
                    {'description': 'Block Storage'},
                    {'description': '0.25 IOPS per GB'},
                    {'description': '20 GB Storage Space'},
                    {'description': '10 GB Storage Space (Snapshot Space)'}]
                }
        }

        result = self.run_command(['block', 'volume-order',
                                   '--storage-type=endurance', '--size=20',
                                   '--tier=0.25', '--os-type=linux',
                                   '--location=dal05', '--snapshot-size=10'])

        self.assert_no_fail(result)
        self.assertEqual(result.output,
                         'Order #478 placed successfully!\n'
                         ' > Endurance Storage\n > Block Storage\n'
                         ' > 0.25 IOPS per GB\n > 20 GB Storage Space\n'
                         ' > 10 GB Storage Space (Snapshot Space)\n')

    @mock.patch('SoftLayer.BlockStorageManager.order_block_volume')
    def test_volume_order_order_not_placed(self, order_mock):
        order_mock.return_value = {}

        result = self.run_command(['block', 'volume-order',
                                   '--storage-type=endurance', '--size=20',
                                   '--tier=0.25', '--os-type=linux',
                                   '--location=dal05'])

        self.assert_no_fail(result)
        self.assertEqual(result.output,
                         'Order could not be placed! Please verify '
                         'your options and try again.\n')

    def test_enable_snapshots(self):
        result = self.run_command(['block', 'snapshot-enable', '12345678',
                                   '--schedule-type=HOURLY', '--minute=10',
                                   '--retention-count=5'])

        self.assert_no_fail(result)

    def test_disable_snapshots(self):
        result = self.run_command(['block', 'snapshot-disable', '12345678',
                                   '--schedule-type=HOURLY'])
        self.assert_no_fail(result)

    def test_create_snapshot(self):
        result = self.run_command(['block', 'snapshot-create', '12345678'])

        self.assert_no_fail(result)

    @mock.patch('SoftLayer.BlockStorageManager.create_snapshot')
    def test_create_snapshot_unsuccessful(self, snapshot_mock):
        snapshot_mock.return_value = []

        result = self.run_command(['block', 'snapshot-create', '8', '-n=note'])

        self.assertEqual('Error occurred while creating snapshot.\n'
                         'Ensure volume is not failed over or in another '
                         'state which prevents taking snapshots.\n',
                         result.output)

    def test_snapshot_list(self):
        result = self.run_command(['block', 'snapshot-list', '12345678'])

        self.assert_no_fail(result)
        self.assertEqual([
            {
                'id': 470,
                'name': 'unit_testing_note',
                'created': '2016-07-06T07:41:19-05:00',
                'size_bytes': '42',
            }],
            json.loads(result.output))

    def test_snapshot_cancel(self):
        result = self.run_command(['--really',
                                   'block', 'snapshot-cancel', '1234'])

        self.assert_no_fail(result)
        self.assertEqual('Block volume with id 1234 has been marked'
                         ' for snapshot cancellation\n', result.output)
        self.assert_called_with('SoftLayer_Billing_Item', 'cancelItem',
                                args=(False, True, None))

    def test_snapshot_restore(self):
        result = self.run_command(['block', 'snapshot-restore', '12345678',
                                   '--snapshot-id=87654321'])

        self.assert_no_fail(result)
        self.assertEqual(result.output, 'Block volume 12345678 is being'
                         ' restored using snapshot 87654321\n')

    @mock.patch('SoftLayer.BlockStorageManager.order_snapshot_space')
    def test_snapshot_order(self, order_mock):
        order_mock.return_value = {
            'placedOrder': {
                'id': 8702,
                'items': [{'description':
                           '10 GB Storage Space (Snapshot Space)'}],
                'status': 'PENDING_APPROVAL',
                }
        }

        result = self.run_command(['block', 'snapshot-order', '1234',
                                   '--capacity=10', '--tier=0.25'])

        self.assert_no_fail(result)
        self.assertEqual(result.output,
                         'Order #8702 placed successfully!\n'
                         ' > 10 GB Storage Space (Snapshot Space)\n'
                         ' > Order status: PENDING_APPROVAL\n')

    def test_authorize_host_to_volume(self):
        result = self.run_command(['block', 'access-authorize', '12345678',
                                   '--hardware-id=100', '--virtual-id=10',
                                   '--ip-address-id=192',
                                   '--ip-address=192.3.2.1'])

        self.assert_no_fail(result)

    def test_deauthorize_host_to_volume(self):
        result = self.run_command(['block', 'access-revoke', '12345678',
                                   '--hardware-id=100', '--virtual-id=10',
                                   '--ip-address-id=192',
                                   '--ip-address=192.3.2.1'])

        self.assert_no_fail(result)

    def test_replicant_failover(self):
        result = self.run_command(['block', 'replica-failover', '12345678',
                                   '--replicant-id=5678', '--immediate'])

        self.assert_no_fail(result)
        self.assertEqual('Failover to replicant is now in progress.\n',
                         result.output)

    @mock.patch('SoftLayer.BlockStorageManager.failover_to_replicant')
    def test_replicant_failover_unsuccessful(self, failover_mock):
        failover_mock.return_value = False

        result = self.run_command(['block', 'replica-failover', '12345678',
                                   '--replicant-id=5678'])

        self.assertEqual('Failover operation could not be initiated.\n',
                         result.output)

    def test_replicant_failback(self):
        result = self.run_command(['block', 'replica-failback', '12345678',
                                   '--replicant-id=5678'])

        self.assert_no_fail(result)
        self.assertEqual('Failback from replicant is now in progress.\n',
                         result.output)

    @mock.patch('SoftLayer.BlockStorageManager.failback_from_replicant')
    def test_replicant_failback_unsuccessful(self, failback_mock):
        failback_mock.return_value = False

        result = self.run_command(['block', 'replica-failback', '12345678',
                                   '--replicant-id=5678'])

        self.assertEqual('Failback operation could not be initiated.\n',
                         result.output)

    @mock.patch('SoftLayer.BlockStorageManager.order_replicant_volume')
    def test_replicant_order_order_not_placed(self, order_mock):
        order_mock.return_value = {}

        result = self.run_command(['block', 'replica-order', '100',
                                   '--snapshot-schedule=DAILY',
                                   '--location=dal05'])

        self.assert_no_fail(result)
        self.assertEqual(result.output,
                         'Order could not be placed! Please verify '
                         'your options and try again.\n')

    @mock.patch('SoftLayer.BlockStorageManager.order_replicant_volume')
    def test_replicant_order(self, order_mock):
        order_mock.return_value = {
            'placedOrder': {
                'id': 91604,
                'items': [
                    {'description': 'Endurance Storage'},
                    {'description': '2 IOPS per GB'},
                    {'description': 'Block Storage'},
                    {'description': '20 GB Storage Space'},
                    {'description': '10 GB Storage Space (Snapshot Space)'},
                    {'description': '20 GB Storage Space Replicant of: TEST'},
                ],
            }
        }

        result = self.run_command(['block', 'replica-order', '100',
                                   '--snapshot-schedule=DAILY',
                                   '--location=dal05', '--tier=2'])

        self.assert_no_fail(result)
        self.assertEqual(result.output,
                         'Order #91604 placed successfully!\n'
                         ' > Endurance Storage\n'
                         ' > 2 IOPS per GB\n'
                         ' > Block Storage\n'
                         ' > 20 GB Storage Space\n'
                         ' > 10 GB Storage Space (Snapshot Space)\n'
                         ' > 20 GB Storage Space Replicant of: TEST\n')


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * xFrameworkPX_Validation_AlphaNumericTest Class File
 *
 * PHP versions 5
 *
 * @category   Tests
 * @package    xFrameworkPX_Validation
 * @author     Kazuhiro Kotsutsumi <kotsutsumi@xenophy.com>
 * @copyright  Copyright (c) 2006-2010 Xenophy.CO.,LTD All rights Reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @version    SVN $Id: AlphaNumericTest.php 956 2009-12-25 14:46:27Z tamari $
 */

// {{{ requires

set_include_path(get_include_path() . PATH_SEPARATOR . '../../library');

/**
 * Require Files
 */
require_once 'PHPUnit/Framework.php';

require_once 'xFrameworkPX/Validation/AlphaNumeric.php';

// }}}
// {{{ xFrameworkPX_Validation_AlphaNumericTest

/**
 * xFrameworkPX_Validation_AlphaNumericTest Class
 *
 * @category   Tests
 * @package    xFrameworkPX_Validation
 * @author     Kazuhiro Kotsutsumi <kotsutsumi@xenophy.com>
 * @copyright  Copyright (c) 2006-2010 Xenophy.CO.,LTD All rights Reserved.
 * @license    http://www.opensource.org/licenses/mit-license.html MIT License
 * @version    Release: @package_version@
 * @link       http://www.xframeworkpx.com/api/
 */
class xFrameworkPX_Validation_AlphaNumericTest
extends PHPUnit_Framework_TestCase
{

    // {{{ setUp

    /**
     * セットアップ
     *
     * @return void
     */
    protected function setUp()
    {

    }

    // }}}
    // {{{ tearDown

    /**
     * 終了処理
     *
     * @return void
     */
    protected function tearDown()
    {

    }

    // }}}
    // {{{ testValidate

    /**
     * validateテスト
     *
     * 半角英数のみ許可
     *
     * @return void
     */
    public function testValidate()
    {

        // {{{ --------------false--------------

        // {{{ 全角ひらがな混じりで入力

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate('てすとtest55')
        );

        // }}}
        // {{{ 全角数字混じりで入力

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate('1test55')
        );

        // }}}
        // {{{ 全角カナ混じりで入力

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate('テストtest55')
        );

        // }}}
        // {{{ 半角カナ混じりで入力

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate('テストtest55')
        );

        // }}}
        // {{{ 半角記号混じりで入力

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate('<test>55')
        );

        // }}}

        // }}}
        // {{{ --------------true--------------

        // {{{ 空文字(NotEmptyでチェックするため)

        $this->assertTrue(
            xFrameworkPX_Validation_AlphaNumeric::validate('')
        );

        // }}}
        // {{{ 半角数字混じりで入力

        $this->assertTrue(
            xFrameworkPX_Validation_AlphaNumeric::validate('11test')
        );

        // }}}
        // {{{ 半角英字のみで入力

        $this->assertTrue(
            xFrameworkPX_Validation_AlphaNumeric::validate('test')
        );

        // }}}

        // }}}
        // {{{ --------------check--------------

        // {{{ 半角スペースのみはfalse

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate(' ')
        );

        // }}}
        // {{{ 全角スペースのみはfalse

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate(' ')
        );

        // }}}
        // {{{ 半角スペース混じりはfalse

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate('te st12')
        );

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate(' test12')
        );

        // }}}
        // {{{ 全角スペース混じりはfalse

        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate('te st12')
        );
        $this->assertFalse(
            xFrameworkPX_Validation_AlphaNumeric::validate(' test12')
        );

        // }}}

    }

    // }}}

}

// }}}

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * c-hanging-comment-ender-p: nil
 * End:
 */


text:
<?php

class SpecialitiesModel extends BaseModel
{
    protected $tableName = "specialities";
}


text:
<!DOCTYPE html>

    <title>CSS Values and Units Test: Viewport units in scaled viewport</title>
    <meta charset="UTF-8">
    <meta name="assert" content="viewport relative units scale with viewport.">
    <link rel="author"  title="Emil A Eklund" href="mailto:eae@chromium.org">
    <link rel="help" href="http://www.w3.org/TR/css3-values/#viewport-relative-lengths">


text:
package org.workcraft.dom.math;

import java.util.ArrayList;
import java.util.Collection;

import org.workcraft.dom.Container;
import org.workcraft.dom.DefaultGroupImpl;
import org.workcraft.dom.Node;
import org.workcraft.dom.hierarchy.NamespaceProvider;
import org.workcraft.dom.references.HierarchicalUniqueNameReferenceManager;
import org.workcraft.dom.references.ReferenceManager;
import org.workcraft.observation.HierarchyObserver;
import org.workcraft.observation.ObservableHierarchy;
import org.workcraft.util.Hierarchy;

public class MathGroup extends MathNode implements NamespaceProvider, ObservableHierarchy {
    private final DefaultGroupImpl groupImpl = new DefaultGroupImpl(this);

    @Override
    public void add(Node node) {
        groupImpl.add(node);
    }

    @Override
    public void addObserver(HierarchyObserver obs) {
        groupImpl.addObserver(obs);
    }

    @Override
    public Collection<Node> getChildren() {
        return groupImpl.getChildren();
    }

    @Override
    public Node getParent() {
        return groupImpl.getParent();
    }

    @Override
    public void remove(Node node) {
        groupImpl.remove(node);
    }

    @Override
    public void removeObserver(HierarchyObserver obs) {
        groupImpl.removeObserver(obs);
    }

    @Override
    public void removeAllObservers() {
        groupImpl.removeAllObservers();
    }

    @Override
    public void setParent(Node parent) {
        groupImpl.setParent(parent);
    }

    @Override
    public void add(Collection<Node> nodes) {
        groupImpl.add(nodes);
    }

    @Override
    public void remove(Collection<Node> nodes) {
        groupImpl.remove(nodes);
    }

    @Override
    public void reparent(Collection<Node> nodes, Container newParent) {
        groupImpl.reparent(nodes, newParent);
    }

    @Override
    public void reparent(Collection<Node> nodes) {
        groupImpl.reparent(nodes);
    }

    public ArrayList<Node> unGroup(ReferenceManager manager) {
        ArrayList<Node> nodesToReparent = new ArrayList<>(groupImpl.getChildren());
        Container newParent = Hierarchy.getNearestAncestor(getParent(), Container.class);
        if (manager != null) {
            if (manager instanceof HierarchicalUniqueNameReferenceManager) {
                HierarchicalUniqueNameReferenceManager hierManager = (HierarchicalUniqueNameReferenceManager) manager;
                NamespaceProvider provider = hierManager.getNamespaceProvider(newParent);
                hierManager.setNamespaceProvider(nodesToReparent, provider);
            }
        }
        groupImpl.reparent(nodesToReparent, newParent);
        return nodesToReparent;
    }

}


text:
#include "port_layer.h"
#include "koc_lock.h"
#include "plasoc_int.h"
#include "plasoc_timer.h"
#include "plasoc_gpio.h"
#include "plasoc_uart.h"

#define HW_LOCK_BASE_ADDRESS		(0x20000000)
#define HW_INT_BASE_ADDRESS		(0x20010000)
#define HW_TIMER_BASE_ADDRESS	(0x20020000)
#define HW_GPIO_BASE_ADDRESS		(0x20030000)
#define HW_UART_BASE_ADDRESS	(0x20040000)
#define INT_TIMER_ID			(0)
#define INT_GPIO_ID			(1)
#define INT_UART_ID				(2)
#define INT_MASK			((1<<INT_TIMER_ID)|(1<<INT_UART_ID))
#define CPUINT_SIGNAL_ID	(KOC_CPU_SIGNAL_INT_ID)
#define CPUINT_INT_ID		(7)
#define CPUINT_MASK			((1<<CPUINT_SIGNAL_ID)|(1<<CPUINT_INT_ID))
#define TIMER_1MS_TICKS		(50000)
#define UART_FIFO_DEPTH			(512)

koc_lock lock_obj;
plasoc_int int_obj;
plasoc_timer timer_obj;
plasoc_gpio gpio_obj;
plasoc_uart uart_obj;

volatile unsigned char uart_fifo[UART_FIFO_DEPTH];
volatile unsigned uart_in_ptr = 0;
volatile unsigned uart_out_ptr = 0;

volatile unsigned timer_1ms_cntr = 0;

/* Define the CPU's service routine such that it calls the
 interrupt controller's service method. */
void int_isr(void* param)
{
	(void) param;
	plasoc_int_service_interrupts(&int_obj);
}

/* Service the uart input. */
void uart_isr(void* ptr)
{
	unsigned byte;
	unsigned next_uart_in_ptr;

	byte = plasoc_uart_get_in(&uart_obj);
	next_uart_in_ptr = (uart_in_ptr+1)%UART_FIFO_DEPTH;
	if (next_uart_in_ptr!=uart_out_ptr)
	{
		uart_fifo[uart_in_ptr] = (unsigned char)byte;
		uart_in_ptr = next_uart_in_ptr;
	}
}

/* Service the timer. */
void timer_isr(void* ptr)
{
	plasoc_timer_reload_start(&timer_obj,1);
	timer_1ms_cntr++;
	l1_cache_flush_range((unsigned)&timer_1ms_cntr,sizeof(timer_1ms_cntr));
}

void putc_port(void* p, char c)
{
	while (!plasoc_uart_get_status_out_avail(&uart_obj));
	plasoc_uart_set_out(&uart_obj,(unsigned)c);
}

void initialize()
{
	{
		koc_lock_setup(&lock_obj,HW_LOCK_BASE_ADDRESS);
		plasoc_timer_setup(&timer_obj,HW_TIMER_BASE_ADDRESS);
		plasoc_uart_setup(&uart_obj,HW_UART_BASE_ADDRESS);
		plasoc_gpio_setup(&gpio_obj,HW_GPIO_BASE_ADDRESS);
		init_printf(0,putc_port);
		plasoc_timer_set_trig_value(&timer_obj,TIMER_1MS_TICKS);
	}

	{
		plasoc_int_setup(&int_obj,HW_INT_BASE_ADDRESS);
		plasoc_int_attach_isr(&int_obj,INT_UART_ID,uart_isr,0);
		plasoc_int_attach_isr(&int_obj,INT_TIMER_ID,timer_isr,0);
		plasoc_int_attach_isr(cpuint(),CPUINT_INT_ID,int_isr,0);
	}

	{
		plasoc_int_enable(cpuint(),CPUINT_INT_ID);
		plasoc_int_set_enables(&int_obj,INT_MASK);
		plasoc_timer_reload_start(&timer_obj,0);

		OS_AsmInterruptInit();
		OS_AsmInterruptEnable(1);
	}
}

void cleanup()
{
	OS_AsmInterruptEnable(0);
	plasoc_int_set_enables(&int_obj,0);
	plasoc_int_disable(cpuint(),CPUINT_INT_ID);
}

void setbyte(unsigned byte)
{
	while (!plasoc_uart_get_status_out_avail(&uart_obj));
	plasoc_uart_set_out(&uart_obj,byte);
}

unsigned getbyte()
{
	unsigned byte;

	while (1)
	{
		register unsigned int_mask;
		int_mask = enter_critical();
		if (uart_in_ptr!=uart_out_ptr)
		{
			byte = (unsigned)uart_fifo[uart_out_ptr];
			uart_out_ptr = (uart_out_ptr+1)%UART_FIFO_DEPTH;
			leave_critical(int_mask);
			break;
		}
		leave_critical(int_mask);
	}

	return byte;
}

void setword(unsigned word)
{
	unsigned each_byte;
	for (each_byte=0;each_byte<4;each_byte++)
	{
		setbyte(word&0xff);
		word >>= 8;
	}
}

unsigned getword()
{
	unsigned each_byte;
	unsigned word = 0;
	for (each_byte=0;each_byte<sizeof(unsigned);each_byte++)
		word = word|(getbyte()<<(each_byte*8));
	return word;
}

void setout(unsigned value)
{
	plasoc_gpio_set_data_out(&gpio_obj,value);
}

unsigned getout()
{
	return plasoc_gpio_get_data_out(&gpio_obj);
}

unsigned getin()
{
	return plasoc_gpio_get_data_in(&gpio_obj);
}

void blocklock()
{
	while (koc_lock_take(&lock_obj)==0)
		continue;
	l1_cache_memory_barrier();
}

void givelock()
{
	l1_cache_memory_barrier();
	koc_lock_give(&lock_obj);
}

void waituntil(unsigned tick)
{
	while (tick!=gettick())
		continue;
}

unsigned gettick()
{
	l1_cache_memory_barrier();
	return timer_1ms_cntr;
}


text:
package daemon

import (
	"context"
	"os"
	"path/filepath"

	"github.com/containerd/containerd/content"
	"github.com/containerd/containerd/content/local"
	"github.com/containerd/containerd/leases"
	"github.com/containerd/containerd/metadata"
	"github.com/containerd/containerd/namespaces"
	"github.com/opencontainers/go-digest"
	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/pkg/errors"
	"go.etcd.io/bbolt"
)

func (daemon *Daemon) configureLocalContentStore(ns string) (content.Store, leases.Manager, error) {
	if err := os.MkdirAll(filepath.Join(daemon.root, "content"), 0700); err != nil {
		return nil, nil, errors.Wrap(err, "error creating dir for content store")
	}
	db, err := bbolt.Open(filepath.Join(daemon.root, "content", "metadata.db"), 0600, nil)
	if err != nil {
		return nil, nil, errors.Wrap(err, "error opening bolt db for content metadata store")
	}
	cs, err := local.NewStore(filepath.Join(daemon.root, "content", "data"))
	if err != nil {
		return nil, nil, errors.Wrap(err, "error setting up content store")
	}
	md := metadata.NewDB(db, cs, nil)
	daemon.mdDB = db
	return namespacedContentProvider(md.ContentStore(), ns), namespacedLeaseManager(metadata.NewLeaseManager(md), ns), nil
}

// withDefaultNamespace sets the given namespace on the context if the current
// context doesn't hold any namespace
func withDefaultNamespace(ctx context.Context, namespace string) context.Context {
	if _, ok := namespaces.Namespace(ctx); ok {
		return ctx
	}
	return namespaces.WithNamespace(ctx, namespace)
}

type namespacedContent struct {
	ns       string
	provider content.Store
}

// Delete removes the content from the store.
func (cp namespacedContent) Delete(ctx context.Context, dgst digest.Digest) error {
	return cp.provider.Delete(withDefaultNamespace(ctx, cp.ns), dgst)
}

// Info will return metadata about content available in the content store.
//
// If the content is not present, ErrNotFound will be returned.
func (cp namespacedContent) Info(ctx context.Context, dgst digest.Digest) (content.Info, error) {
	return cp.provider.Info(withDefaultNamespace(ctx, cp.ns), dgst)
}

// Update updates mutable information related to content.
// If one or more fieldpaths are provided, only those
// fields will be updated.
// Mutable fields:
//
//	labels.*
func (cp namespacedContent) Update(ctx context.Context, info content.Info, fieldpaths ...string) (content.Info, error) {
	return cp.provider.Update(withDefaultNamespace(ctx, cp.ns), info, fieldpaths...)
}

// Walk will call fn for each item in the content store which
// match the provided filters. If no filters are given all
// items will be walked.
func (cp namespacedContent) Walk(ctx context.Context, fn content.WalkFunc, filters ...string) error {
	return cp.provider.Walk(withDefaultNamespace(ctx, cp.ns), fn, filters...)
}

// Abort completely cancels the ingest operation targeted by ref.
func (cp namespacedContent) Abort(ctx context.Context, ref string) error {
	return cp.provider.Abort(withDefaultNamespace(ctx, cp.ns), ref)
}

// ListStatuses returns the status of any active ingestions whose ref match the
// provided regular expression. If empty, all active ingestions will be
// returned.
func (cp namespacedContent) ListStatuses(ctx context.Context, filters ...string) ([]content.Status, error) {
	return cp.provider.ListStatuses(withDefaultNamespace(ctx, cp.ns), filters...)
}

// Status returns the status of the provided ref.
func (cp namespacedContent) Status(ctx context.Context, ref string) (content.Status, error) {
	return cp.provider.Status(withDefaultNamespace(ctx, cp.ns), ref)
}

// Some implementations require WithRef to be included in opts.
func (cp namespacedContent) Writer(ctx context.Context, opts ...content.WriterOpt) (content.Writer, error) {
	return cp.provider.Writer(withDefaultNamespace(ctx, cp.ns), opts...)
}

// ReaderAt only requires desc.Digest to be set.
// Other fields in the descriptor may be used internally for resolving
// the location of the actual data.
func (cp namespacedContent) ReaderAt(ctx context.Context, desc ocispec.Descriptor) (content.ReaderAt, error) {
	return cp.provider.ReaderAt(withDefaultNamespace(ctx, cp.ns), desc)
}

// namespacedContentProvider sets the namespace if missing before calling the inner provider
func namespacedContentProvider(provider content.Store, ns string) content.Store {
	return namespacedContent{
		ns,
		provider,
	}
}

type namespacedLeases struct {
	ns      string
	manager leases.Manager
}

// AddResource references the resource by the provided lease.
func (nl namespacedLeases) AddResource(ctx context.Context, lease leases.Lease, resource leases.Resource) error {
	return nl.manager.AddResource(withDefaultNamespace(ctx, nl.ns), lease, resource)
}

// Create creates a new lease using the provided lease
func (nl namespacedLeases) Create(ctx context.Context, opt ...leases.Opt) (leases.Lease, error) {
	return nl.manager.Create(withDefaultNamespace(ctx, nl.ns), opt...)
}

// Delete deletes the lease with the provided lease ID
func (nl namespacedLeases) Delete(ctx context.Context, lease leases.Lease, opt ...leases.DeleteOpt) error {
	return nl.manager.Delete(withDefaultNamespace(ctx, nl.ns), lease, opt...)
}

// DeleteResource dereferences the resource by the provided lease.
func (nl namespacedLeases) DeleteResource(ctx context.Context, lease leases.Lease, resource leases.Resource) error {
	return nl.manager.DeleteResource(withDefaultNamespace(ctx, nl.ns), lease, resource)
}

// List lists all active leases
func (nl namespacedLeases) List(ctx context.Context, filter ...string) ([]leases.Lease, error) {
	return nl.manager.List(withDefaultNamespace(ctx, nl.ns), filter...)
}

// ListResources lists all the resources referenced by the lease.
func (nl namespacedLeases) ListResources(ctx context.Context, lease leases.Lease) ([]leases.Resource, error) {
	return nl.manager.ListResources(withDefaultNamespace(ctx, nl.ns), lease)
}

// namespacedLeaseManager sets the namespace if missing before calling the inner manager
func namespacedLeaseManager(manager leases.Manager, ns string) leases.Manager {
	return namespacedLeases{
		ns,
		manager,
	}
}


text:
var Foo = /*#__PURE__*/function (_Bar) {
  "use strict";

  babelHelpers.inherits(Foo, _Bar);

  function Foo() {
    var _this;

    babelHelpers.classCallCheck(this, Foo);

    if (condition) {
      _this = babelHelpers.possibleConstructorReturn(this, babelHelpers.getPrototypeOf(Foo).call(this));
      babelHelpers.defineProperty(babelHelpers.assertThisInitialized(_this), "bar", "foo");
    } else {
      _this = babelHelpers.possibleConstructorReturn(this, babelHelpers.getPrototypeOf(Foo).call(this));
      babelHelpers.defineProperty(babelHelpers.assertThisInitialized(_this), "bar", "foo");
    }

    return babelHelpers.possibleConstructorReturn(_this);
  }

  return Foo;
}(Bar);