text:
#pragma once

#include <lib/support/EnforceFormat.h>
#include <platform/DeviceInfoProvider.h>
//#include <platform/nxp/mw320/MW320Config.h>

namespace chip {
namespace DeviceLayer {

class DeviceInfoProviderImpl : public DeviceInfoProvider
{
public:
    DeviceInfoProviderImpl() = default;
    ~DeviceInfoProviderImpl() override {}

    // Iterators
    FixedLabelIterator * IterateFixedLabel(EndpointId endpoint) override;
    UserLabelIterator * IterateUserLabel(EndpointId endpoint) override;
    SupportedLocalesIterator * IterateSupportedLocales() override;
    SupportedCalendarTypesIterator * IterateSupportedCalendarTypes() override;

    static DeviceInfoProviderImpl & GetDefaultInstance();

protected:
    class FixedLabelIteratorImpl : public FixedLabelIterator
    {
    public:
        FixedLabelIteratorImpl(EndpointId endpoint);
        size_t Count() override;
        bool Next(FixedLabelType & output) override;
        void Release() override { delete this; }

    private:
        EndpointId mEndpoint = 0;
        size_t mIndex        = 0;
        char mFixedLabelNameBuf[kMaxLabelNameLength + 1];
        char mFixedLabelValueBuf[kMaxLabelValueLength + 1];
    };

    class UserLabelIteratorImpl : public UserLabelIterator
    {
    public:
        UserLabelIteratorImpl(DeviceInfoProviderImpl & provider, EndpointId endpoint);
        size_t Count() override { return mTotal; }
        bool Next(UserLabelType & output) override;
        void Release() override { delete this; }

    private:
        DeviceInfoProviderImpl & mProvider;
        EndpointId mEndpoint = 0;
        size_t mIndex        = 0;
        size_t mTotal        = 0;
        char mUserLabelNameBuf[kMaxLabelNameLength + 1];
        char mUserLabelValueBuf[kMaxLabelValueLength + 1];
    };

    class SupportedLocalesIteratorImpl : public SupportedLocalesIterator
    {
    public:
        SupportedLocalesIteratorImpl() = default;
        size_t Count() override;
        bool Next(CharSpan & output) override;
        void Release() override { delete this; }

    private:
        size_t mIndex = 0;
        char mActiveLocaleBuf[kMaxActiveLocaleLength + 1];
    };

    class SupportedCalendarTypesIteratorImpl : public SupportedCalendarTypesIterator
    {
    public:
        SupportedCalendarTypesIteratorImpl() = default;
        size_t Count() override;
        bool Next(CalendarType & output) override;
        void Release() override { delete this; }

    private:
        size_t mIndex = 0;
    };

    CHIP_ERROR SetUserLabelLength(EndpointId endpoint, size_t val) override;
    CHIP_ERROR GetUserLabelLength(EndpointId endpoint, size_t & val) override;
    CHIP_ERROR SetUserLabelAt(EndpointId endpoint, size_t index, const UserLabelType & userLabel) override;
    CHIP_ERROR DeleteUserLabelAt(EndpointId endpoint, size_t index) override;

private:
    static constexpr size_t UserLabelTLVMaxSize() { return TLV::EstimateStructOverhead(kMaxLabelNameLength, kMaxLabelValueLength); }
};

} // namespace DeviceLayer
} // namespace chip


text:
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <corners android:bottomLeftRadius="5dp" android:bottomRightRadius="5dp" android:topLeftRadius="5dp" android:topRightRadius="5dp"/>
            <stroke android:width="1dp" android:color="@color/actionbar_color2" />
        </shape>
    </item>
    <item android:bottom="1dp" android:left="1dp" android:top="1dp" android:right="1dp">
        <shape>
            <padding android:left="5dp"
                android:top="3dp"
                android:right="5dp"
                android:bottom="3dp" />
            <corners android:bottomLeftRadius="4dp" android:bottomRightRadius="4dp" android:topLeftRadius="4dp" android:topRightRadius="4dp"/>
            <solid android:color="@color/blue_3" />
        </shape>
    </item>
</layer-list>

redpajama_set_name: RedPajamaGithub


text:
<Ui xmlns="http://www.blizzard.com/wow/ui/"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
    <Script file="enUS.lua"/>
    <Script file="ruRU.lua"/>
</Ui>


text:
void
Init_GMagick(void)
{
  gm_ID_trace_proc = rb_intern("@trace_proc");
  gm_ID_ID_call = rb_intern("call");

  Module_Gmagick = rb_define_module("Gmagick");
  Class_Image = rb_define_class_under(Module_GMagick, "Image", rb_cObject);

  rb_define_alloc_func(Class_Image, Image_alloc);
  rb_define_privete_method(Class_Image, "initialize", Image_Initialize, -1);

}


text:
'use strict';

Object.defineProperty(exports, '__esModule', {
  value: true
});
var _bind = Function.prototype.bind;

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

var _commonStatement = require('./common/Statement');

var _commonStatement2 = _interopRequireDefault(_commonStatement);

var _commonObjectCreator = require('./common/ObjectCreator');

var _commonObjectCreator2 = _interopRequireDefault(_commonObjectCreator);

var Service = (function () {
  function Service(soapService) {
    _classCallCheck(this, Service);

    this.waitingOperations = [];
    this.setSoapService(soapService);

    this.serviceName = this.constructor.name.replace(/Service$/, '');
  }

  _createClass(Service, [{
    key: 'createStatement',
    value: function createStatement(query) {
      if (typeof query === 'string') {
        return { filterStatement: { query: query } };
      }

      if (!query) {
        return { filterStatement: { query: '' } };
      }

      var statement = new _commonStatement2['default'](query);

      return { filterStatement: statement.createStatement() };
    }
  }, {
    key: 'list',
    value: function list(query) {
      return this.callAsync('get' + this.serviceName + 'sByStatement', this.createStatement(query));
    }
  }, {
    key: 'setSoapService',
    value: function setSoapService(soapService) {
      var _this = this;

      this.soapService = soapService;

      Object.keys(soapService).forEach(function (method) {
        if (!(method in _this)) {
          _this[method] = function () {
            for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }

            return _this.callAsync.apply(_this, [method].concat(args));
          };
        }
      });

      if (this.initialize) {
        this.initialize();
      }

      return this;
    }
  }, {
    key: 'callAsync',
    value: function callAsync(method) {
      for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        args[_key2 - 1] = arguments[_key2];
      }

      var fn = this.soapService[method];

      return new Promise(function (resolve, reject) {
        fn.apply(undefined, _toConsumableArray(args.concat([function (err, res) {
          if (err) {
            reject(err);
          } else {
            if (res && 'rval' in res) {
              res = res.rval;
            }

            resolve(res);
          }
        }])));
      });
    }
  }, {
    key: 'createObject',
    value: function createObject() {
      for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
        args[_key3] = arguments[_key3];
      }

      return new (_bind.apply(_commonObjectCreator2['default'], [null].concat(args)))();
    }
  }, {
    key: 'findOrCreate',
    value: function findOrCreate(obj) {
      var _this2 = this;

      return this.list('WHERE name = \'' + obj.name + '\'').then(function (res) {
        if (res && res.results) {
          return res.results[0];
        }

        return _this2.create(obj);
      });
    }
  }]);

  return Service;
})();

exports['default'] = Service;
module.exports = exports['default'];


text:
import { ActivatedRoute, Data } from '@angular/router';
import { Component } from '@angular/core';
import { inject, TestBed } from '@angular/core/testing';

// Load the implementations that should be tested
import { DemoComponent } from './demo.component';

describe(`Demo`, () => {
  // provide our implementations or mocks to the dependency injector
  beforeEach(() => TestBed.configureTestingModule({
    providers: [
      // provide a better mock
      {
        provide: ActivatedRoute,
        useValue: {
          data: {
            subscribe: (fn: (value: Data) => void) => fn({
              yourData: 'yolo'
            })
          }
        }
      },
      DemoComponent
    ]
  }));

  it('should log ngOnInit', inject([DemoComponent], (demoComponent: DemoComponent) => {
    spyOn(console, 'log');
    expect(console.log).not.toHaveBeenCalled();

    demoComponent.ngOnInit();
    expect(console.log).toHaveBeenCalled();
  }));

});


text:
\hypertarget{clientSocket_8hpp}{}\section{lib/socket/client\+Socket.hpp File Reference}
\label{clientSocket_8hpp}\index{lib/socket/client\+Socket.\+hpp@{lib/socket/client\+Socket.\+hpp}}
{\ttfamily \#include $<$functional$>$}\newline
{\ttfamily \#include $<$netinet/in.\+h$>$}\newline
{\ttfamily \#include $<$stdint.\+h$>$}\newline
{\ttfamily \#include $<$sys/types.\+h$>$}\newline
\subsection*{Classes}
\begin{DoxyCompactItemize}
\item
struct \hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t}
\end{DoxyCompactItemize}
\subsection*{Functions}
\begin{DoxyCompactItemize}
\item
\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} \hyperlink{clientSocket_8hpp_ae862f25be64781717805cf0374ea8d10}{client\+Socket\+\_\+open\+Socket} (uint16\+\_\+t port)
\item
void \hyperlink{clientSocket_8hpp_ab12176036cae40fab7223f425d2120d1}{client\+Socket\+\_\+request\+Dialogue} (\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$, void $\ast$hello, size\+\_\+t len, std\+::function$<$ void(\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$)$>$ func, const uint8\+\_\+t targetop)
\item
ssize\+\_\+t \hyperlink{clientSocket_8hpp_a1616c2bb3206971a3771d614394189ab}{client\+Socket\+\_\+send} (const void $\ast$msg, size\+\_\+t len, \hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$s)
\item
void \hyperlink{clientSocket_8hpp_aa0693d0d2f2e5693d448c728876d5ece}{client\+Socket\+\_\+listen} (\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$s, std\+::function$<$ void(\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$)$>$ func)
\end{DoxyCompactItemize}

\subsection{Function Documentation}
\mbox{\Hypertarget{clientSocket_8hpp_aa0693d0d2f2e5693d448c728876d5ece}\label{clientSocket_8hpp_aa0693d0d2f2e5693d448c728876d5ece}}
\index{client\+Socket.\+hpp@{client\+Socket.\+hpp}!client\+Socket\+\_\+listen@{client\+Socket\+\_\+listen}}
\index{client\+Socket\+\_\+listen@{client\+Socket\+\_\+listen}!client\+Socket.\+hpp@{client\+Socket.\+hpp}}
\subsubsection{\texorpdfstring{client\+Socket\+\_\+listen()}{clientSocket\_listen()}}
{\footnotesize\ttfamily void client\+Socket\+\_\+listen (\begin{DoxyParamCaption}\item[{\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$}]{s,  }\item[{std\+::function$<$ void(\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$)$>$}]{func }\end{DoxyParamCaption})}

\mbox{\Hypertarget{clientSocket_8hpp_ae862f25be64781717805cf0374ea8d10}\label{clientSocket_8hpp_ae862f25be64781717805cf0374ea8d10}}
\index{client\+Socket.\+hpp@{client\+Socket.\+hpp}!client\+Socket\+\_\+open\+Socket@{client\+Socket\+\_\+open\+Socket}}
\index{client\+Socket\+\_\+open\+Socket@{client\+Socket\+\_\+open\+Socket}!client\+Socket.\+hpp@{client\+Socket.\+hpp}}
\subsubsection{\texorpdfstring{client\+Socket\+\_\+open\+Socket()}{clientSocket\_openSocket()}}
{\footnotesize\ttfamily \hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} client\+Socket\+\_\+open\+Socket (\begin{DoxyParamCaption}\item[{uint16\+\_\+t}]{port }\end{DoxyParamCaption})}

\mbox{\Hypertarget{clientSocket_8hpp_ab12176036cae40fab7223f425d2120d1}\label{clientSocket_8hpp_ab12176036cae40fab7223f425d2120d1}}
\index{client\+Socket.\+hpp@{client\+Socket.\+hpp}!client\+Socket\+\_\+request\+Dialogue@{client\+Socket\+\_\+request\+Dialogue}}
\index{client\+Socket\+\_\+request\+Dialogue@{client\+Socket\+\_\+request\+Dialogue}!client\+Socket.\+hpp@{client\+Socket.\+hpp}}
\subsubsection{\texorpdfstring{client\+Socket\+\_\+request\+Dialogue()}{clientSocket\_requestDialogue()}}
{\footnotesize\ttfamily void client\+Socket\+\_\+request\+Dialogue (\begin{DoxyParamCaption}\item[{\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$}]{,  }\item[{void $\ast$}]{hello,  }\item[{size\+\_\+t}]{len,  }\item[{std\+::function$<$ void(\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$)$>$}]{func,  }\item[{const uint8\+\_\+t}]{targetop }\end{DoxyParamCaption})}

\mbox{\Hypertarget{clientSocket_8hpp_a1616c2bb3206971a3771d614394189ab}\label{clientSocket_8hpp_a1616c2bb3206971a3771d614394189ab}}
\index{client\+Socket.\+hpp@{client\+Socket.\+hpp}!client\+Socket\+\_\+send@{client\+Socket\+\_\+send}}
\index{client\+Socket\+\_\+send@{client\+Socket\+\_\+send}!client\+Socket.\+hpp@{client\+Socket.\+hpp}}
\subsubsection{\texorpdfstring{client\+Socket\+\_\+send()}{clientSocket\_send()}}
{\footnotesize\ttfamily ssize\+\_\+t client\+Socket\+\_\+send (\begin{DoxyParamCaption}\item[{const void $\ast$}]{msg,  }\item[{size\+\_\+t}]{len,  }\item[{\hyperlink{structcubiumClientSocket__t}{cubium\+Client\+Socket\+\_\+t} $\ast$}]{s }\end{DoxyParamCaption})}


text:
<TITLE>Review for Private Parts (1997)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Private Parts (1997)

reviewed by
Steve Rhodes

                               PRIVATE PARTS
                       A film review by Steve Rhodes
                        Copyright 1997 Steve Rhodes

I saw Howard Stern's movie at the press screening, and I laughed
through almost every minute of it.  The film opens nationwide this
coming Friday, March 7.

RATING (0 TO ****):  ****

     First, let me assure my loyal readers that I have not been cloned.
My evil twin is not the one writing this review, and I have not lost my
mind.

     First, confessions are in order.  Before seeing Howard Stern's
movie, called PRIVATE PARTS, I had never seen nor listened to Howard
Stern even for a single minute.  Moreover, I was absolutely sure that
I had no desire to ever see him.  I was so sure that his humor would be
gross and mean spirited that if there had been a conflict with another
press screening, as there frequently is, I would have gone to see the
other film instead -- any other film.

     Well, PRIVATE PARTS was the biggest pleasant surprise for me in a
quite a while.  Yes, the film is certainly outrageous, but so was
AIRPLANE! (1980).  And yes, Howard is shocking.  I would postulate that
Howard Stern is one of the funniest and sweetest people around.
Although I laughed so hard that I even got choked, the biggest surprise
for me was how tender and good spirited the show is even at its most
audacious.  The plot even contains the long lasting love story between
Howard and Alison, his wife of twenty years.  (All of Howard's
entourage in the film, with the exception of Alison, are played by
themselves.  Alison is acted by Mary McCormack.)

     PRIVATE PARTS is the autobiography of Howard's life and is based
on his book.  In the first part, his father Ben (Richard Portnow) tells
Howard at every opportunity how moronic he is.  "We never went to
ballgames," reminisces Howard.  "The only sport my dad liked was
yelling."  This gave Howard his tough skin and his obsession with being
liked.  Howard's antics, like those of any class clown, are disguised,
plaintive cries to be wanted and be popular.

     His ability to simultaneously disgust and involve an audience is
seen when he is twelve.  He gives a traditional puppet show at a senior
citizen's home that has them all dropping like flies.  He decides to
jazz up the act with simulated puppet sex.  Needless to say, the
audience is so shocked and enraged that they can't take their eyes off
the stage.

     Howard's movie isn't just about Howard.  The film is careful to
focus in on his supporting crew, especially Robin Quivers and Fred
Norris.  The first to join him was cherubic looking black newscaster
Robin Quivers.  The rules of the time were that the DJ did his shtick,
and when it came time, they switched to the newscaster.  From the first
day, Howard pulled Robin into his comedic fray.  She is as sweet as
sweet can be, but she can hold her own.  In her own more subtle way,
she manages to top Howard in the banter on the air.  Robin gives a
marvelously compelling performance in the film.

     Although much of the show does happen on the air, a large portion
is devoted to Howard's constant battles with management.  When he
finally works his way to the top -- the biggest radio station in New
York -- the NBC lawyers read him the riot act.  There are seven words
you can not say on the air so he must stop saying them.  So what does
he do?  In arguably the funniest scene in the show, he devises a match
game where he picks a common word and lets his coworkers guess the
missing, and, if taken out of context, obscene word that goes with it.
(For example, if I say Hoover, you would say Dam.  This is not used in
the movie, but it is the only G rated one I could think of to give you
the idea.)  His nemesis and personal watch dog manager, Kenny (played
with angry fervor by Paul Giamatti), goes ballistic when Howard
violates the rules.  Howard becomes vindictive and refers to Kenny on
the air only as Pig Vomit.

     NBC executive Roger Erlick (Michael Murphy) says that "Howard is
on the FCC's Most Wanted List."  NBC wants to fire him, but there is a
problem.  He has become the hottest DJ in the nation.  How long does
the average listener stay tuned to the same station?  18 minutes.  For
Howard it is an hour and twenty minutes.  Well, how about the Howard
haters, the managers ask, since there are a lot of those?  Over two
hours.  In both cases the reason is that listeners want to know "what
will he say next?"

     "After all, being misunderstood is the fate of all true geniuses
is it not?"  laments Howard.  Even earning a fortune and having
millions of fans, he still worries that people will think he is just a
moron.

     I do not want to mislead you.  The show manages to insult just
about everyone.  Still, the humor is non-stop, and based on the theater
audience's reactions, people respond extremely well to his jokes.  Go
with an open mind, and you may not be able to control yourself.
Howard's film raises comedy to a new level.  I will reject the urge to
recount more of the film's crazy antics and let you experience it
yourself as I did.

     As I left the theater I began to recount my favorite scene to my
friend I had taken with me.  As soon as I laughed my way through one, I
kept remembering another that was even better.  If the film had had one
tenth the humor or one fourth the likeableness of its stars, I would
have counted it a success.  The movie it most reminded of was PEOPLE
VS. LARRY FLYNT, but I liked PRIVATE PARTS better.

     An incredible and unique experience.  An infectiously happy show.
Howard teaches us to laugh at everything in life.  And yes, by the end
we have fallen in love with him, his comedic conspirators, and just
about everyone associated with the production.  A more likable group I
haven't seen in a long time.

     PRIVATE PARTS flies by at 1:49.  (Stay through the final credits,
for the film keeps coming back on.)  It is rated R for strong language,
dope smoking, crude sexual humor, and nudity.  Teenagers will probably
love it, but make sure they are mature enough for the material.  I give
the film my strongest recommendation and my top rating of ****.

**** = A must see film.
***  = Excellent show.  Look for it.
**   = Average movie.  Kind of enjoyable.
*    = Poor show.  Don't waste your money.
0    = Totally and painfully unbearable picture.

REVIEW WRITTEN ON: March 3, 1997

Opinions expressed are mine and not meant to reflect my employer's.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
<?php

namespace Lexik\Bundle\FormFilterBundle\Tests\Filter\Doctrine;
use Lexik\Bundle\FormFilterBundle\Filter\Doctrine\ORMQuery;
use Doctrine\ORM\QueryBuilder;
use PHPUnit\Framework\TestCase;

/**
 * @author Cédric Girard <c.girard@lexik.fr>
 */
class ORMQueryTest extends TestCase
{
    public function testHasJoinAlias()
    {
        $emMock = $this->getMockBuilder('Doctrine\ORM\EntityManager')
            ->disableOriginalConstructor()
            ->getMock();

        $emMock
            ->expects($this->any())
            ->method('getExpressionBuilder')
            ->will($this->returnValue(new \Doctrine\ORM\Query\Expr()));

        $qb = new QueryBuilder($emMock);
        $qb->from('Root', 'r');
        $qb->leftJoin('r.association1', 'a1');
        $qb->leftJoin('r.association2', 'a2');
        $qb->innerJoin('a2.association22', 'a22');

        $query = new ORMQuery($qb);

        $this->assertTrue($query->hasJoinAlias('a2'));
        $this->assertFalse($query->hasJoinAlias('a3'));
    }
}


text:
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#endregion

namespace RolePlaying
{
    /// <summary>
    /// Base class for screens that contain a menu of options. The user can
    /// move up and down to select an entry, or cancel to back out of the screen.
    /// </summary>
    /// <remarks>
    /// Similar to a class found in the Game State Management sample on the
    /// XNA Creators Club Online website (http://creators.xna.com).
    /// </remarks>
    abstract class MenuScreen : GameScreen
    {
        #region Fields

        List<MenuEntry> menuEntries = new List<MenuEntry>();
        protected int selectedEntry = 0;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the list of menu entries, so derived classes can add
        /// or change the menu contents.
        /// </summary>
        protected IList<MenuEntry> MenuEntries
        {
            get { return menuEntries; }
        }

        protected MenuEntry SelectedMenuEntry
        {
            get
            {
                if ((selectedEntry < 0) || (selectedEntry >= menuEntries.Count))
                {
                    return null;
                }
                return menuEntries[selectedEntry];
            }
        }

        #endregion

        #region Initialization

        /// <summary>
        /// Constructor.
        /// </summary>
        public MenuScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(0.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
        }

        #endregion

        #region Handle Input

        /// <summary>
        /// Responds to user input, changing the selected entry and accepting
        /// or cancelling the menu.
        /// </summary>
        public override void HandleInput()
        {
            int oldSelectedEntry = selectedEntry;

            // Move to the previous menu entry?
            if (InputManager.IsActionTriggered(InputManager.Action.CursorUp))
            {
                selectedEntry--;
                if (selectedEntry < 0)
                    selectedEntry = menuEntries.Count - 1;
            }

            // Move to the next menu entry?
            if (InputManager.IsActionTriggered(InputManager.Action.CursorDown))
            {
                selectedEntry++;
                if (selectedEntry >= menuEntries.Count)
                    selectedEntry = 0;
            }

            // Accept or cancel the menu?
            if (InputManager.IsActionTriggered(InputManager.Action.Ok))
            {
                AudioManager.PlayCue("Continue");
                OnSelectEntry(selectedEntry);
            }
            else if (InputManager.IsActionTriggered(InputManager.Action.Back) ||
                InputManager.IsActionTriggered(InputManager.Action.ExitGame))
            {
                OnCancel();
            }
            else if (selectedEntry != oldSelectedEntry)
            {
                AudioManager.PlayCue("MenuMove");
            }
        }

        /// <summary>
        /// Handler for when the user has chosen a menu entry.
        /// </summary>
        protected virtual void OnSelectEntry(int entryIndex)
        {
            menuEntries[selectedEntry].OnSelectEntry();
        }

        /// <summary>
        /// Handler for when the user has cancelled the menu.
        /// </summary>
        protected virtual void OnCancel()
        {
            ExitScreen();
        }

        /// <summary>
        /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler.
        /// </summary>
        protected void OnCancel(object sender, EventArgs e)
        {
            OnCancel();
        }

        #endregion

        #region Update and Draw

        /// <summary>
        /// Updates the menu.
        /// </summary>
        public override void Update(GameTime gameTime, bool otherScreenHasFocus,
                                                       bool coveredByOtherScreen)
        {
            base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);

            // Update each nested MenuEntry object.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                bool isSelected = IsActive && (i == selectedEntry);

                menuEntries[i].Update(this, isSelected, gameTime);
            }
        }

        /// <summary>
        /// Draws the menu.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;

            spriteBatch.Begin();

            // Draw each menu entry in turn.
            for (int i = 0; i < menuEntries.Count; i++)
            {
                MenuEntry menuEntry = menuEntries[i];

                bool isSelected = IsActive && (i == selectedEntry);

                menuEntry.Draw(this, isSelected, gameTime);
            }

            spriteBatch.End();
        }

        #endregion
    }
}


text:
using System;
using System.Text;
using MichaelTCC.Infrastructure.Protocol;

namespace MichaelTCC.Domain.Protocol
{
    internal class ConvertProtocol
    {
        internal static string MichaelProtocolToString(IMichaelProtocol michaelProtocol)
        {
            var sb = new StringBuilder();
            sb.Append("S;");
            sb.Append(Convert.ToInt32(michaelProtocol.Up));
            sb.Append(";");
            sb.Append(Convert.ToInt32(michaelProtocol.Down));
            sb.Append(";");
            sb.Append(Convert.ToInt32(michaelProtocol.Left));
            sb.Append(";");
            sb.Append(Convert.ToInt32(michaelProtocol.Right));
            sb.Append(";");
            sb.Append(Convert.ToInt32(michaelProtocol.iOS));
            sb.Append(";");
            sb.Append(Convert.ToInt32(michaelProtocol.Triangle));
            sb.Append(";");
            sb.Append(Convert.ToInt32(michaelProtocol.A));
            sb.Append(";");
            sb.Append(Convert.ToInt32(michaelProtocol.X));
            sb.Append(";");

            foreach (float values in michaelProtocol.SensorValues)
            {
                sb.Append(string.Format("{0:0.00}", values));
                sb.Append(";");
            }

            sb.Append(Convert.ToInt32(michaelProtocol.Button1));
            sb.Append(";CR");

            return sb.ToString();
        }

        internal static IDataReceiveProtocol BytesToIDataReceiveProtocol(byte[] data)
        {
            string dataString = Encoding.UTF8.GetString(data, 0, data.Length);
            string[] campos = dataString.Split(';');
            if(campos.Length != 7)
                return new DataReceiveProtocol();
            return new DataReceiveProtocol
            {
                Campo1 = campos[1],
                Campo2 = campos[2],
                Campo3 = campos[3],
                Campo4 = campos[4],
                Campo5 = campos[5],
            };
        }
    }
}


text:
{-# OPTIONS_GHC -fbang-patterns #-}

module HMQ.Example.GeneratedEntities.Employees where

import Data.List
import Data.Maybe
import System.Time
import Database.HDBC

import HMQ.Metadata.TableMetadata
import HMQ.Query hiding(tableIdentifier)
import HMQ.ForeignKeyLink
import HMQ.MappedQuery
import HMQ.RowValueExtractors

data Employee =
    Employee
     {
          employeeId :: Integer,
          lastName :: String,
          firstName :: String,
          ssn :: String,
          phone :: String,
          birthDate :: CalendarTime,
          managerId :: Integer,
          storeId :: Integer
     }
     deriving (Show)

-- The extractor function which creates an Employee from a result row.
rowValueExtractor ::  EntityRowValueExtractor Employee
rowValueExtractor !tableAlias !qry =
    let
        leadingColIx = fromMaybe (error $ "No columns for table alias " ++ tableAlias ++ " found in query.") $
                                 findIndex ((tableAlias ++ ".") `isPrefixOf`) (selectFieldExprs qry)
    in
      leadingColIx `seq`
          (\(!row) ->
              let
                  fv1:fv2:fv3:fv4:fv5:fv6:fv7:fv8:_ = drop leadingColIx row
              in
                -- Check first pk field to determine if there's a value for this row
                if fv1 == SqlNull then
                    Nothing
                else
                    Just $ Employee (fromSql fv1) (fromSql fv2) (fromSql fv3) (fromSql fv4) (fromSql fv5) (fromSql fv6) (fromSql fv7) (fromSql fv8)
          )

tableMetadata :: TableMetadata
tableMetadata =
    TableMetadata {
     tableIdentifier = TableIdentifier {tableSchema = Just "public", tableName = "employees"},
     fieldMetadatas =
       [
           FieldMetadata {fieldName = "employee_id", fieldSqlColDesc = SqlColDesc {colType = SqlBigIntT, colSize = Just 4, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}},
           FieldMetadata {fieldName = "last_name", fieldSqlColDesc = SqlColDesc {colType = SqlVarCharT, colSize = Just 50, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}},
           FieldMetadata {fieldName = "first_name", fieldSqlColDesc = SqlColDesc {colType = SqlVarCharT, colSize = Just 50, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}},
           FieldMetadata {fieldName = "ssn", fieldSqlColDesc = SqlColDesc {colType = SqlCharT, colSize = Just 9, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}},
           FieldMetadata {fieldName = "phone", fieldSqlColDesc = SqlColDesc {colType = SqlVarCharT, colSize = Just 12, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}},
           FieldMetadata {fieldName = "birth_date", fieldSqlColDesc = SqlColDesc {colType = SqlDateT, colSize = Just 4, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}},
           FieldMetadata {fieldName = "manager_id", fieldSqlColDesc = SqlColDesc {colType = SqlBigIntT, colSize = Just 4, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}},
           FieldMetadata {fieldName = "store_id", fieldSqlColDesc = SqlColDesc {colType = SqlBigIntT, colSize = Just 4, colOctetLength = Nothing, colDecDigits = Nothing, colNullable = Just False}}
       ],
     primaryKeyFieldNames = ["employee_id"],
     foreignKeyConstraints = [ForeignKeyConstraint {sourceTable = TableIdentifier {tableSchema = Just "public", tableName = "employees"}, targetTable = TableIdentifier {tableSchema = Just "public", tableName = "employees"}, equatedFields = [("manager_id","employee_id")]},ForeignKeyConstraint {sourceTable = TableIdentifier {tableSchema = Just "public", tableName = "employees"}, targetTable = TableIdentifier {tableSchema = Just "public", tableName = "stores"}, equatedFields = [("store_id","store_id")]}]
}

mappedQuery :: MappedQuery Employee Employee Employee
mappedQuery = MappedTable tableMetadata rowValueExtractor


text:
using System.Collections.Generic;
using Azure.Core;

namespace Azure.ResourceManager.Resources.Models
{
    /// <summary> The type of the paths for alias. </summary>
    public partial class AliasPath
    {
        /// <summary> Initializes a new instance of AliasPath. </summary>
        internal AliasPath()
        {
            ApiVersions = new ChangeTrackingList<string>();
        }

        /// <summary> Initializes a new instance of AliasPath. </summary>
        /// <param name="path"> The path of an alias. </param>
        /// <param name="apiVersions"> The API versions. </param>
        /// <param name="pattern"> The pattern for an alias path. </param>
        internal AliasPath(string path, IReadOnlyList<string> apiVersions, AliasPattern pattern)
        {
            Path = path;
            ApiVersions = apiVersions;
            Pattern = pattern;
        }

        /// <summary> The path of an alias. </summary>
        public string Path { get; }
        /// <summary> The API versions. </summary>
        public IReadOnlyList<string> ApiVersions { get; }
        /// <summary> The pattern for an alias path. </summary>
        public AliasPattern Pattern { get; }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
    <channel>
        <title>Prepare to Improvise</title>
        <link>http://znseaman.github.io/</link>
        <description>a blog of Zach Seaman</description>
        <language>en-us</language>
        <pubDate>Tue, 26 Nov 2013 00:00:00 -0600</pubDate>

        <item>
            <link>http://znseaman.github.io/2013/11/26/expectation.html</link>
            <guid>http://znseaman.github.io/2013/11/26/expectation.html</guid>
            <title><![CDATA[Expectation]]></title>
            <description><![CDATA[

Expectation

'Fluctuation is aching my soul, Expectation is taking its toll', sings Kevin Parker in Tame Impala's Expectation. October of 2012, I took a big step when I moved to Mexico City, focused on Spanish and international development. More than a year later, I'm still here and with a change in expectation.

Expectation can be crippling. We learn to believe it should be this way or that. We cannot accept one thing or another. For the last year, I have expected too much of myself.

When I got here, I didn't know about open source geographic information systems (GIS). My previous proprietary GIS software knowledge guided me to a learn a different way of working. I dove in and began working in QGIS, a packaged "under the hood" introduction to the open source tools of all GIS software: a great find for a technical junkie like myself. Though I wanted to go deeper, past the graphical interface of QGIS and into the command line. All the while, work was asking for JavaScript, PostgreSQL/PostGIS, and Python. I wanted to learn it all overnight: a very unhealthy expectation.

And I tried. Spending hours upon hours on weekends and spare time, reading and experimenting. Like a Doctor Who episode, I attempted to absorb all the technical stuff (i.e. ogr2ogr, PostgreSQL, JavaScript, Python, GitHub, and more). Everything was in flux and my expectation took its toll in the form of stress. Things had to change. I decided to scale back my expectation and build small.

How? Taking one small step at a time. I remind myself, at 24, that I just got here. I'm practicing Python until I'm comfortable enough to improvise. Technology, in constant flux, is difficult to learn and I am modifying my expectations to do so. If you feel overwhelmed, scale back your expectations and build small.

]]></description>
            <category><![CDATA[ Writing ]]></category>
             <pubDate>Tue, 26 Nov 2013 00:00:00 -0600</pubDate>
        </item>

        <item>
            <link>http://znseaman.github.io/2013/11/24/welcome.html</link>
            <guid>http://znseaman.github.io/2013/11/24/welcome.html</guid>
            <title><![CDATA[Welcome]]></title>
            <description><![CDATA[

Welcome

Hello There, Internet. This is my first entry to my newly established site and blog using Tinkerer. Topics will most likely include programming, geographic information systems (GIS), and other interests.

]]></description>
            <category><![CDATA[ Writing ]]></category>
             <pubDate>Sun, 24 Nov 2013 00:00:00 -0600</pubDate>
        </item>

    </channel>
</rss>


text:
#include "mitkAnnotation.h"
#include "usGetModuleContext.h"

const std::string mitk::Annotation::US_INTERFACE_NAME = "org.mitk.services.Annotation";
const std::string mitk::Annotation::US_PROPKEY_AnnotationNAME = US_INTERFACE_NAME + ".name";
const std::string mitk::Annotation::US_PROPKEY_ID = US_INTERFACE_NAME + ".id";
const std::string mitk::Annotation::US_PROPKEY_MODIFIED = US_INTERFACE_NAME + ".modified";
const std::string mitk::Annotation::US_PROPKEY_RENDERER_ID = US_INTERFACE_NAME + ".rendererId";
const std::string mitk::Annotation::US_PROPKEY_AR_ID = US_INTERFACE_NAME + ".arId";

mitk::Annotation::Annotation() : m_PropertyListModifiedObserverTag(0)
{
  m_PropertyList = mitk::PropertyList::New();
  itk::MemberCommand<mitk::Annotation>::Pointer _PropertyListModifiedCommand =
    itk::MemberCommand<mitk::Annotation>::New();
  _PropertyListModifiedCommand->SetCallbackFunction(this, &mitk::Annotation::PropertyListModified);
  m_PropertyListModifiedObserverTag = m_PropertyList->AddObserver(itk::ModifiedEvent(), _PropertyListModifiedCommand);
  this->SetName(this->GetNameOfClass());
  this->SetVisibility(true);
  this->SetOpacity(1.0);
}

void mitk::Annotation::PropertyListModified(const itk::Object * /*caller*/, const itk::EventObject &)
{
  AnnotationModified();
}

mitk::Annotation::~Annotation()
{
  this->UnRegisterMicroservice();
}

void mitk::Annotation::SetUSProperty(const std::string &propertyKey, us::Any value)
{
  if (this->m_ServiceRegistration)
  {
    us::ServiceProperties props;
    std::vector<std::string> propertyKeys;
    m_ServiceRegistration.GetReference().GetPropertyKeys(propertyKeys);
    for (std::string key : propertyKeys)
    {
      props[key] = m_ServiceRegistration.GetReference().GetProperty(key);
    }
    props[propertyKey] = value;
    m_ServiceRegistration.SetProperties(props);
  }
}

void mitk::Annotation::SetProperty(const std::string &propertyKey, const BaseProperty::Pointer &propertyValue)
{
  this->m_PropertyList->SetProperty(propertyKey, propertyValue);
}

void mitk::Annotation::ReplaceProperty(const std::string &propertyKey, const BaseProperty::Pointer &propertyValue)
{
  this->m_PropertyList->ReplaceProperty(propertyKey, propertyValue);
}

void mitk::Annotation::AddProperty(const std::string &propertyKey,
                                   const BaseProperty::Pointer &propertyValue,
                                   bool overwrite)
{
  if ((overwrite) || (GetProperty(propertyKey) == nullptr))
  {
    SetProperty(propertyKey, propertyValue);
  }
}

void mitk::Annotation::ConcatenatePropertyList(PropertyList *pList, bool replace)
{
  m_PropertyList->ConcatenatePropertyList(pList, replace);
}

mitk::BaseProperty *mitk::Annotation::GetProperty(const std::string &propertyKey) const
{
  mitk::BaseProperty::Pointer property = m_PropertyList->GetProperty(propertyKey);
  if (property.IsNotNull())
    return property;

  // only to satisfy compiler!
  return nullptr;
}

bool mitk::Annotation::GetBoolProperty(const std::string &propertyKey, bool &boolValue) const
{
  mitk::BoolProperty::Pointer boolprop = dynamic_cast<mitk::BoolProperty *>(GetProperty(propertyKey));
  if (boolprop.IsNull())
    return false;

  boolValue = boolprop->GetValue();
  return true;
}

bool mitk::Annotation::GetIntProperty(const std::string &propertyKey, int &intValue) const
{
  mitk::IntProperty::Pointer intprop = dynamic_cast<mitk::IntProperty *>(GetProperty(propertyKey));
  if (intprop.IsNull())
    return false;

  intValue = intprop->GetValue();
  return true;
}

bool mitk::Annotation::GetFloatProperty(const std::string &propertyKey, float &floatValue) const
{
  mitk::FloatProperty::Pointer floatprop = dynamic_cast<mitk::FloatProperty *>(GetProperty(propertyKey));
  if (floatprop.IsNull())
    return false;

  floatValue = floatprop->GetValue();
  return true;
}

bool mitk::Annotation::GetStringProperty(const std::string &propertyKey, std::string &string) const
{
  mitk::StringProperty::Pointer stringProp = dynamic_cast<mitk::StringProperty *>(GetProperty(propertyKey));
  if (stringProp.IsNull())
  {
    return false;
  }
  else
  {
    // memcpy((void*)string, stringProp->GetValue(), strlen(stringProp->GetValue()) + 1 ); // looks dangerous
    string = stringProp->GetValue();
    return true;
  }
}

void mitk::Annotation::SetIntProperty(const std::string &propertyKey, int intValue)
{
  this->m_PropertyList->SetProperty(propertyKey, mitk::IntProperty::New(intValue));
  Modified();
}
void mitk::Annotation::SetBoolProperty(const std::string &propertyKey, bool boolValue)
{
  this->m_PropertyList->SetProperty(propertyKey, mitk::BoolProperty::New(boolValue));
  Modified();
}

void mitk::Annotation::SetFloatProperty(const std::string &propertyKey, float floatValue)
{
  this->m_PropertyList->SetProperty(propertyKey, mitk::FloatProperty::New(floatValue));
  Modified();
}

void mitk::Annotation::SetDoubleProperty(const std::string &propertyKey, double doubleValue)
{
  this->m_PropertyList->SetProperty(propertyKey, mitk::DoubleProperty::New(doubleValue));
  Modified();
}

void mitk::Annotation::SetStringProperty(const std::string &propertyKey, const std::string &stringValue)
{
  this->m_PropertyList->SetProperty(propertyKey, mitk::StringProperty::New(stringValue));
  Modified();
}

std::string mitk::Annotation::GetName() const
{
  mitk::StringProperty *sp = dynamic_cast<mitk::StringProperty *>(this->GetProperty("name"));
  if (sp == nullptr)
    return "";
  return sp->GetValue();
}

void mitk::Annotation::SetName(const std::string &name)
{
  this->SetStringProperty("name", name);
}

bool mitk::Annotation::GetName(std::string &nodeName, const std::string &propertyKey) const
{
  return GetStringProperty(propertyKey, nodeName);
}

void mitk::Annotation::SetText(std::string text)
{
  SetStringProperty("Text", text.c_str());
}

std::string mitk::Annotation::GetText() const
{
  std::string text;
  GetStringProperty("Text", text);
  return text;
}

void mitk::Annotation::SetFontSize(int fontSize)
{
  SetIntProperty("FontSize", fontSize);
}

int mitk::Annotation::GetFontSize() const
{
  int fontSize = 1;
  GetIntProperty("FontSize", fontSize);
  return fontSize;
}

bool mitk::Annotation::GetVisibility(bool &visible, const std::string &propertyKey) const
{
  return GetBoolProperty(propertyKey, visible);
}

bool mitk::Annotation::IsVisible(const std::string &propertyKey, bool defaultIsOn) const
{
  return IsOn(propertyKey, defaultIsOn);
}

bool mitk::Annotation::GetColor(float rgb[], const std::string &propertyKey) const
{
  mitk::ColorProperty::Pointer colorprop = dynamic_cast<mitk::ColorProperty *>(GetProperty(propertyKey));
  if (colorprop.IsNull())
    return false;

  memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3 * sizeof(float));
  return true;
}

void mitk::Annotation::SetColor(const mitk::Color &color, const std::string &propertyKey)
{
  mitk::ColorProperty::Pointer prop;
  prop = mitk::ColorProperty::New(color);
  this->m_PropertyList->SetProperty(propertyKey, prop);
}

void mitk::Annotation::SetColor(float red, float green, float blue, const std::string &propertyKey)
{
  float color[3];
  color[0] = red;
  color[1] = green;
  color[2] = blue;
  SetColor(color, propertyKey);
}

void mitk::Annotation::SetColor(const float rgb[], const std::string &propertyKey)
{
  mitk::ColorProperty::Pointer prop;
  prop = mitk::ColorProperty::New(rgb);
  this->m_PropertyList->SetProperty(propertyKey, prop);
}

bool mitk::Annotation::GetOpacity(float &opacity, const std::string &propertyKey) const
{
  mitk::FloatProperty::Pointer opacityprop = dynamic_cast<mitk::FloatProperty *>(GetProperty(propertyKey));
  if (opacityprop.IsNull())
    return false;

  opacity = opacityprop->GetValue();
  return true;
}

void mitk::Annotation::SetOpacity(float opacity, const std::string &propertyKey)
{
  mitk::FloatProperty::Pointer prop;
  prop = mitk::FloatProperty::New(opacity);
  this->m_PropertyList->SetProperty(propertyKey, prop);
}

void mitk::Annotation::SetVisibility(bool visible, const std::string &propertyKey)
{
  mitk::BoolProperty::Pointer prop;
  prop = mitk::BoolProperty::New(visible);
  this->m_PropertyList->SetProperty(propertyKey, prop);
  Modified();
}

bool mitk::Annotation::BaseLocalStorage::IsGenerateDataRequired(mitk::BaseRenderer *renderer,
                                                                mitk::Annotation *Annotation)
{
  if (m_LastGenerateDataTime < Annotation->GetMTime())
    return true;

  if (m_LastGenerateDataTime < Annotation->GetPropertyList()->GetMTime())
    return true;

  if (renderer && m_LastGenerateDataTime < renderer->GetTimeStepUpdateTime())
    return true;

  return false;
}

mitk::Annotation::Bounds mitk::Annotation::GetBoundsOnDisplay(mitk::BaseRenderer *) const
{
  mitk::Annotation::Bounds bounds;
  bounds.Position[0] = bounds.Position[1] = bounds.Size[0] = bounds.Size[1] = 0;
  return bounds;
}

void mitk::Annotation::SetBoundsOnDisplay(mitk::BaseRenderer *, const mitk::Annotation::Bounds &)
{
}

void mitk::Annotation::SetForceInForeground(bool forceForeground)
{
  m_ForceInForeground = forceForeground;
}

bool mitk::Annotation::IsForceInForeground() const
{
  return m_ForceInForeground;
}

mitk::PropertyList *mitk::Annotation::GetPropertyList() const
{
  return m_PropertyList;
}

std::string mitk::Annotation::GetMicroserviceID()
{
  return this->m_ServiceRegistration.GetReference().GetProperty(US_PROPKEY_ID).ToString();
}

void mitk::Annotation::RegisterAsMicroservice(us::ServiceProperties props)
{
  if (m_ServiceRegistration != nullptr)
    m_ServiceRegistration.Unregister();
  us::ModuleContext *context = us::GetModuleContext();
  // Define ServiceProps
  mitk::UIDGenerator uidGen = mitk::UIDGenerator("org.mitk.services.Annotation.id_", 16);
  props[US_PROPKEY_ID] = uidGen.GetUID();
  m_ServiceRegistration = context->RegisterService(this, props);
}

void mitk::Annotation::UnRegisterMicroservice()
{
  if (m_ServiceRegistration != nullptr)
    m_ServiceRegistration.Unregister();
  m_ServiceRegistration = 0;
}

void mitk::Annotation::AnnotationModified()
{
  Modified();
  this->SetUSProperty(US_PROPKEY_MODIFIED, this->GetMTime());
}


text:
/**
 * @flow
 */
import React, { Component } from 'react'
import styles from './ColumnSizer.example.css'
import AutoSizer from '../AutoSizer'
import ColumnSizer from './ColumnSizer'
import Grid from '../Grid'
import { ContentBox, ContentBoxHeader, ContentBoxParagraph } from '../demo/ContentBox'
import { LabeledInput, InputRow } from '../demo/LabeledInput'
import shallowCompare from 'react-addons-shallow-compare'

export default class ColumnSizerExample extends Component {
  constructor (props) {
    super(props)

    this.state = {
      columnMaxWidth: 100,
      columnMinWidth: 75,
      columnCount: 10
    }

    this._noColumnMaxWidthChange = this._noColumnMaxWidthChange.bind(this)
    this._noColumnMinWidthChange = this._noColumnMinWidthChange.bind(this)
    this._onColumnCountChange = this._onColumnCountChange.bind(this)
    this._noContentRenderer = this._noContentRenderer.bind(this)
    this._cellRenderer = this._cellRenderer.bind(this)
  }

  render () {
    const {
      columnMaxWidth,
      columnMinWidth,
      columnCount
    } = this.state

    return (
      <ContentBox {...this.props}>
        <ContentBoxHeader
          text='ColumnSizer'
          sourceLink='https://github.com/bvaughn/react-virtualized/blob/master/source/ColumnSizer/ColumnSizer.example.js'
          docsLink='https://github.com/bvaughn/react-virtualized/blob/master/docs/ColumnSizer.md'
        />

        <ContentBoxParagraph>
          This component decorates a Grid and calculates the width of its columns based on the current (Grid) width.
        </ContentBoxParagraph>

        <InputRow>
          <LabeledInput
            label='Num Columns'
            name='columnCount'
            onChange={this._onColumnCountChange}
            value={columnCount}
          />
          <LabeledInput
            label='Column Min Width'
            name='columnMinWidth'
            onChange={this._noColumnMinWidthChange}
            value={columnMinWidth}
          />
          <LabeledInput
            label='Column Max Width'
            name='columnMaxWidth'
            onChange={this._noColumnMaxWidthChange}
            value={columnMaxWidth}
          />
        </InputRow>

          <AutoSizer disableHeight>
            {({ width }) => (
              <ColumnSizer
                columnMaxWidth={columnMaxWidth}
                columnMinWidth={columnMinWidth}
                columnCount={columnCount}
                key='GridColumnSizer'
                width={width}
              >
                {({ adjustedWidth, getColumnWidth, registerChild }) => (

                    <Grid
                      ref={registerChild}
                      columnWidth={getColumnWidth}
                      columnCount={columnCount}
                      height={50}
                      noContentRenderer={this._noContentRenderer}
                      cellRenderer={this._cellRenderer}
                      rowHeight={50}
                      rowCount={1}
                      width={adjustedWidth}
                    />

                )}
              </ColumnSizer>
            )}
          </AutoSizer>

      </ContentBox>
    )
  }

  shouldComponentUpdate (nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState)
  }

  _noColumnMaxWidthChange (event) {
    let columnMaxWidth = parseInt(event.target.value, 10)

    if (isNaN(columnMaxWidth)) {
      columnMaxWidth = undefined
    } else {
      columnMaxWidth = Math.min(1000, columnMaxWidth)
    }

    this.setState({ columnMaxWidth })
  }

  _noColumnMinWidthChange (event) {
    let columnMinWidth = parseInt(event.target.value, 10)

    if (isNaN(columnMinWidth)) {
      columnMinWidth = undefined
    } else {
      columnMinWidth = Math.max(1, columnMinWidth)
    }

    this.setState({ columnMinWidth })
  }

  _onColumnCountChange (event) {
    this.setState({ columnCount: parseInt(event.target.value, 10) || 0 })
  }

  _noContentRenderer () {
    return (

        No cells

    )
  }

  _cellRenderer ({ columnIndex, rowIndex }) {
    const className = columnIndex === 0
      ? styles.firstCell
      : styles.cell

    return (

        {`R:${rowIndex}, C:${columnIndex}`}

    )
  }
}


text:
<?php

namespace Symfony\Component\Form\Tests\Extension\Validator\Constraints;

use Symfony\Component\Validator\Validation;

/**
 * @author Bernhard Schussek <bschussek@gmail.com>
 * @group  legacy
 */
class LegacyFormValidatorLegacyApiTest extends FormValidatorTest
{
    protected function getApiVersion()
    {
        return Validation::API_VERSION_2_5_BC;
    }
}


text:
package io.github.varvelworld.var.ioc.core.meta;

import java.util.Collections;
import java.util.List;

/**
 * Created by luzhonghao on 2016/12/4.
 */
public class ParamResourcesMeta {

    public static final ParamResourcesMeta EMPTY = new ParamResourcesMeta(Collections.emptyList());

    private final List<ParamResourceMeta> paramResourceMetaList;

    public ParamResourcesMeta(List<ParamResourceMeta> paramResourceMetaList) {
        this.paramResourceMetaList = paramResourceMetaList;
    }

    public List<ParamResourceMeta> paramResourceMetaList() {
        return paramResourceMetaList;
    }
}


text: Microphone Phased Array


text:
/*
 * When the user checks in and checks out of a venue (Pizza Shop)
 * data is written to live feature services on ArcGIS Online.
 *
 * It may be desirable to demonstrate the application without writing to the feature services,
 * and we make use of this global variable to determine whether writing should be abled or not.
 */

var __PREVENT_CHECKINCHECKOUT_WRITE__ = true;

/*
 * To disable writing, set this variable to true.
 *
 * To enable writing, set it to false or delete it.
 */

Ext.define('PF.controller.PizzaShop', {
    extend: 'Ext.app.Controller',

	// Service URL Endpoints.
	directionsServiceURL: "http://tasks.arcgisonline.com/ArcGIS/rest/services/NetworkAnalysis/ESRI_Route_NA/NAServer/Route",
	geometryServiceURL: "http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer",

    requires:[
    	'Ext.MessageBox'
    ],

	config: {
		// Let's define handles onto the various Views we want to control
		refs: {
			pizzaShopPanel: {
				selector: '#pizzaShopDetailsView',
				xtype: 'pizzashop',
				autoCreate: true
			},
			pizzaShopDirectionsPanel: {
				selector: '#pizzaShopDirectionsView',
				xtype: 'pizzashopdirections',
				autoCreate: true
			},
			pizzaShopDirectionButton: {
				selector: '#pizzaShopDetailsView button#getPizzaShopDirections'
			},
			pizzaShopDirectionsList: {
				selector: '#pizzaShopDirectionsView dataview#directionsList'
			},
			pizzaShopCheckinPanel: {
				selector: '#pizzaShopDirectionsView #checkinDetails'
			},
			pizzaShopCheckInCheckOutButton: {
				selector: '#pizzaShopDirectionsView #checkinButton'
			}
		},

		// And now let's attach ourselves to events on some of those Views
		control: {
			pizzaShopDirectionButton: {
				tap: 'showDirections'
			},
			pizzaShopCheckInCheckOutButton: {
				tap: 'checkInCheckOutButtonTapped'
			},
			pizzaShopDirectionsList:{
				select: 'directionItemSelected'
			}
		}
	},

	// Let's define some properties
	pizzaShop:null,

	// Track the user's check-in status
	isCheckedIn:false,
	canCheckIn:false,
	checkInTime:null,
	checkOutTime:null,

	// The code is built to use an arbitrary geofence Polygon to check that the user
	// might check in. However, in this case we'll just generate a radius around the
	// end point (in most cases that's probably reasonable). See also geofenceGeometry.
	checkinTolerance: 25, // Map units - meters for Web Mercator Aux Sphere...

	// Some properties we'll use for turn-by-turn directions
	routeTask:null,
	routeParams:null,
	routeResult:null,

	// Track the current turn-by-turn direction item.
	currentRouteTurn:null,
	currentUserPosition:null,

	// This is an arbitrary polygon we use to determine whether the user is
	// currently close enough to check in (or indeed must be checked out).
	// In this case this is generated using checkinTolerance.
	geofenceGeometry:null,

	// Track where we're getting directions *from* (it's always *to* the pizzaShop).
	fromPt:null,

	// To generate the checkin polygon, we'll use an online geometry service to buffer around the end point.
	geomService: null,

	// Used to handle time-based updates to the UI.
	intervalID:null,

	// Calling this pushes the Pizza Shop Details View into... er... view.
	showDetails: function (pizzaShopGraphic) {
		// When the user clicks on a Pizza Shop in the map, the Main Controller gets notified
		// and calls this function - this is really the Pizza Shop "entry point"
		this.getPizzaShopPanel().setPizzaShop(pizzaShopGraphic);

		// BEGIN WORK-AROUND
		// This is a work-around for bug TOUCH-2395 in Sencha Touch 2.0
		// http://www.sencha.com/forum/showthread.php?185646
		var wrapperPanel = Ext.create('Ext.Container', {
			fullscreen: true,
			id:'wrapper-for-touch-2395-bug',
			title: pizzaShopGraphic.attributes['NAME'],
			layout: 'fit'
		});
		wrapperPanel.add(this.getPizzaShopPanel());
		wrapperPanel.down('pizzashop').setHidden(false);
		PF.mainView.push(wrapperPanel);

		// The following line works in 2.0.1 RC but that release has bigger problems.
		// PF.mainView.push(this.getPizzaShopPanel());
		// END WORK-AROUND

		this.pizzaShop = pizzaShopGraphic;
	},

	// This transitions from the Pizza Shop Details View to the Pizza Shop Directions View.
	showDirections: function() {
		// When the user clicks the "Show Directions" button on the details display, this is called.
		// We'll display the Directions panel and then kick off the process of getting directions.
		if (this.pizzaShop)
		{
			// Display the directions panel.
			var myPanel = this.getPizzaShopDirectionsPanel();
			this.getPizzaShopDirectionsPanel().setPizzaShop(this.pizzaShop);
			PF.mainView.push(this.getPizzaShopDirectionsPanel());

			// Lazy load some services and config
			if (!this.geomService) {
				this.geomService = new esri.tasks.GeometryService(this.geometryServiceURL);
			}

			if (!this.routeTask) {
				this.routeTask = new esri.tasks.RouteTask(this.directionsServiceURL);
			}

			if (!this.routeParams) {
	        	var params = new esri.tasks.RouteParameters();
		        params.stops = new esri.tasks.FeatureSet();
		        params.returnRoutes = true;
		        params.returnDirections = true;
		        params.directionsLengthUnits = esri.Units.MILES;
		        params.outSpatialReference = new esri.SpatialReference({ wkid:102100 });

				this.routeParams = params;
			}

			// And calculate directions from the last entered point (could be a Geocode result,
			// a tap on the map, or using the browser's geolocation).
			this.getDirections(PF.lastSearchLocation);
		}
	},

	getDirections: function(fromPt)
	{
		if (this.pizzaShop)
		{
			Ext.Viewport.setMasked({
				xtype:'loadmask',
				message:'Working it out...',
				zIndex: 50
			});

			// Get some parameters for the directions search.
			// We'll store the From Point for later reference if need be.
			this.fromPt = fromPt;
			var toPt = this.pizzaShop.geometry;
			var pizzaShopName = this.pizzaShop.attributes['NAME'];

			//Define the route input parameters
			var params = this.routeParams;
			params.stops.features = [];

			//Add the starting location to the map
			var startLoc = new esri.Graphic(fromPt).setAttributes({ Name: PF.lastSearchText });
			params.stops.features[0] = startLoc;

			//Add the ending location to the map
			var endLoc = new esri.Graphic(toPt).setAttributes({ Name: pizzaShopName });
			params.stops.features[1] = endLoc;

			// Kick off the routing service
			// If this succeeds, we'll drop into routeSolutionFound() below...
			this.routeTask.solve(params, this.routeSolutionFound, this.serviceError);
		}
	},

	routeSolutionFound: function(solveResult) {
		var thisController = PF.app.getController('PizzaShop');

		// Store the route solution step-by-step directions.
		var directions = solveResult.routeResults[0].directions;
		thisController.routeResult = directions;

		var fromPt = thisController.fromPt;
		var toPt = thisController.pizzaShop.geometry;
		// Tell the UI to update itself with various bits and pieces.
		thisController.getPizzaShopDirectionsPanel().setStartAndEndPoints(fromPt, toPt);
		thisController.getPizzaShopDirectionsPanel().setRouteResult(directions);

		// We track the user's position (as they click through the route).
		// Could extend to track realtime GPS location, but this will do for now.
		this.currentUserPosition = fromPt;

		// And calculate (and display) the geofence. We could have done this earlier in
		// the process, but we decided to wait to get a valid set of directions first.
		thisController.calculateAndShowGeofence();

		// And remove the progress mask.
		Ext.Viewport.unmask();
	},

	serviceError:function (error)
	{
		// Something went wrong. This, of course, will never ever get called, right?
		Ext.Viewport.unmask();
		Ext.Msg.alert("Error getting route", error.message);
	},

 	directionItemSelected: function(c,record,opts) {
		// A turn-by-turn item was selected from the UI list.

		// Let's first update the map display.
		this.currentRouteTurn = record.data.dirstep;
		this.getPizzaShopDirectionsPanel().drawCurrentRouteTurn();

		var couldCheckIn = this.isCloseEnoughToCheckIn();

		// We'll assume the user is at the start of the selected segment.
		this.currentUserPosition = this.currentRouteTurn.geometry.getPoint(0,0);

		// Now let's see if that's within the geofence.
		this.canCheckIn = this.isCloseEnoughToCheckIn();

		if (couldCheckIn != this.canCheckIn)
		{
			this.updateGeofence();
		}

		// And if they have to be checked out, let's check them out.
		if (this.isCheckedIn && !this.canCheckIn)
		{
			// We need to automatically check out.
			this.checkOut('automatically');
		}

		// Lastly, update the UI to reflect this.
		this.getPizzaShopDirectionsPanel().updateCheckInControls(this.isCheckedIn, this.canCheckIn);
	},

	checkInCheckOutButtonTapped: function() {
		// The same button is used for check in or check out.
		// We'll rely on other code to ensure the button text matches.
		if (!this.isCheckedIn)
		{
			// Let's check in
			this.checkIn();
		}
		else
		{
			// Let's check out
			this.checkOut();
		}

		// And this code will ensure the button looks correct depending on our check-in status.
		this.getPizzaShopDirectionsPanel().updateCheckInControls(this.isCheckedIn, this.canCheckIn);
	},

	calculateAndShowGeofence: function() {
		// The spatial references are inferred from the toPt.
		var bufParams = new esri.tasks.BufferParameters();
		bufParams.distances = [ this.checkinTolerance ];
		bufParams.geometries = [ this.pizzaShop.geometry ];

		// Since we have a shortcut to the controller, we can set up a reference
		// that the embedded functions below can use as a handle back to the Sencha Controller.
		var thisController = this;

		this.geomService.buffer(bufParams,
			function (geometries) {
				var bufferGeom = geometries[0];
				// Store the generated buffer geometry
				thisController.geofenceGeometry = bufferGeom;

				// Update the UI
				thisController.updateGeofence();
			},
			function (error) {
				Ext.Msg.alert("Geometry Service Error", "Could not generate buffer: " + error.message);
				thisController.geofenceGeometry = null;
			}
		);
	},

	updateGeofence: function() {
		this.getPizzaShopDirectionsPanel().setCheckinGeofence(this.geofenceGeometry, this.isCloseEnoughToCheckIn());
	},

	isCloseEnoughToCheckIn: function(location)
	{
		location = (typeof location == "undefined")?this.currentUserPosition:location;

		var withinGeofence = false;
		if (location)
		{
			if (this.geofenceGeometry)
			{
				// See if we're within the geofence. Again, this is a client-side geometry function.
				withinGeofence = this.geofenceGeometry.contains(location);
			}
			else
			{
				// As a fallback in case the geofence geometry didn't get generated for some reason...
				var destinationPoint = this.pizzaShop.geometry;
				withinGeofence = esri.geometry.getLength(location, destinationPoint) < this.checkinTolerance
			}
		}

		return withinGeofence;
	},

	getRating: function(checkInTime, checkOutTime, distance) {
		// We could, and probably should, come up with something more complex
		// for the rating, based on how long the person was there, etc. etc.
		var baseRating = this.getRatingForDistance(distance);
		var durationFactor = this.getRatingDurationFactor(checkInTime, checkOutTime);

		return Math.min(Math.round(baseRating * durationFactor),5);
	},

	getRatingForDistance: function(distance) {
		var rating = 1;

		if (distance > 0 && distance < 2)
		    rating = 1;
		else if (distance >= 2 && distance < 3)
		    rating = 2;
		else if (distance >= 3 && distance < 4)
		    rating = 3;
		else if (distance >= 4 && distance < 5)
		    rating = 4;
		else if (distance >= 5)
		    rating = 5;

		return rating;
	},

	getRatingDurationFactor: function(checkInTime, checkOutTime) {
		var durationFactor = 1;

		var durationInMinutes = Ext.Date.getElapsed(checkInTime, checkOutTime) / 1000; //60000;

		if (durationInMinutes < 0.5)
			durationFactor = 0.5;
		else if (durationInMinutes < 2)
			durationFactor = 1;
		else if (durationInMinutes < 5)
			durationFactor = 1.1;
		else if (durationInMinutes < 10)
			durationFactor = 1.2;
		else if (durationInMinutes < 15)
			durationFactor = 1.3;
		else if (durationInMinutes < 30)
			durationFactor = 1.4;
		else if (durationInMinutes < 60)
			durationFactor = 1.5;
		else
			durationFactor = 2;

		return durationFactor;
	},

	// Check-in/Check-out functionality

	checkIn: function() {
		// The user is checking in. For this, we just record the time it happened
		// and update the UI.
		var checkInDateTime = new Date();
		this.checkInTime = checkInDateTime;

		// Let the user know we're checking in...
		Ext.Viewport.setMasked({
				xtype:'loadmask',
				message:'Checking in...'
			});

		this.isCheckedIn = true;

		// Update the UI
		this.getPizzaShopDirectionsPanel().showCheckIn(this.checkInTime);

		// Clear the progress display after giving it 1.2 seconds on screen.
		setTimeout(function () { Ext.Viewport.unmask()}, 1200);

		// While they're checked in, let's update the display every second
		// with how long they've been there.
		//
		// Holding on to the handle we get back allows us to cancel the update
		// function when we need to. In the meantime, it'll fire ever 1 second.
		var thisController = this;
		this.intervalID = setInterval(function() {
				thisController.updateCheckinStatus(thisController);
			}, 1000);
	},

	checkOut: function(reason) {
		// CheckOut could be automatic based on the geofence, or
		// a manual click of the Check Out button.
		reason = (typeof reason == "undefined")?'':reason;

		// Stop updating the check-in display.
		clearInterval(this.intervalID);

		// Tidy up the reason code.
		if (reason != '')
		{
			reason = ' ' + reason;
		}

		// Let the user know we're checking out...
		Ext.Viewport.setMasked({
				xtype:'loadmask',
				message:'Checking out' + reason + '...'
			});

		this.checkOutTime = new Date();

		// Prepare some data to write out to our feature services.
		var checkInStartLayer = this.getPizzaShopDirectionsPanel().checkinStartLayer;
		var checkInRouteLayer = this.getPizzaShopDirectionsPanel().checkinRouteLayer;

		var routeGeom = this.routeResult.mergedGeometry;
		var startGeom = this.fromPt;
		if (startGeom == null)
		{
			startGeom = PF.lastSearchLocation;
		}
		var distance = this.routeResult.totalLength;
		var rating = this.getRating(this.checkInTime, this.checkOutTime, distance);

		// And write the data.
		this.writeCheckInCheckOut(checkInStartLayer, startGeom, distance, rating);
		this.writeCheckInCheckOut(checkInRouteLayer, routeGeom, distance, rating);

		// Make a note of our current state.
		this.isCheckedIn = false;

		// Now update the UI
		this.getPizzaShopDirectionsPanel().showCheckOut(this.checkOutTime, rating);

		// And clear the progress display.
		setTimeout(function () { Ext.Viewport.unmask()}, 1200);
	},

	updateCheckinStatus: function(thisController) {
		// Figure out how long we've been checked in.
		var startTime = thisController.checkInTime;
		var msSinceCheckIn = Ext.Date.getElapsed(startTime);

		// And update the UI.
		thisController.getPizzaShopDirectionsPanel().updateCheckInDisplay(msSinceCheckIn);
	},

	writeCheckInCheckOut: function(layer, geom, distance, rating) {
		// Do the work of actually writing our checkin/checkout data to the
		// specified service.
		var graphic = new esri.Graphic(geom);

		// Get some data for the checkin...
		var checkInTime = this.checkInTime;
		var checkOutTime = this.checkOutTime;
		// The check-in duration is in minutes.
		var duration = Ext.Date.getElapsed(checkInTime, checkOutTime) / 60000;

		graphic.attributes = {
			"POI_ID": this.pizzaShop.attributes["POI_ID"],
			"Customer_I": 7,
			"CustomerNa": "Anonymous User",
			"Name": this.pizzaShop.attributes["NAME"],
			"CheckIn": checkInTime.getTime(),
			"CheckOut": checkOutTime.getTime(),
			"Duration": duration,
			"Distance": distance,
			"Rating": rating
		};

		var addGraphics = [ graphic ];

		// See the notes at the top of this file. This variable exists to easily disable
		// writing of checkin/checkout data to ArcGIS Online feature services for the
		// purposes of testing and/or demonstration.
		if (__PREVENT_CHECKINCHECKOUT_WRITE__) return;

		layer.applyEdits(addGraphics, null, null, function(aResults, uResults, dResults)
			{
				console.log("Checkin/out written");
			}, function(error)
			{
				Ext.Msg.alert("Problem Writing Check-In", error.message);
			}
		);
	}
});


text:
using MyVote.UI.Helpers;

namespace MyVote.UI
{
	public class MyVoteApp
	{
		public void Initialize()
		{
            Ioc.Container = new Bootstrapper().Bootstrap();
            //RegisterAppStart(new MvxAppStart());
		}
	}
}


text:
import pytest
import requests
from uuid import uuid4
from json.decoder import JSONDecodeError

from backend.util.response.store.search_results import SearchResultsSchema

def test_find(domain_url, es_create):
    arg = str(uuid4())
    es_create("products", 5, brand=arg)
    es_create("products", 5, kind=arg)

    for ftype in ["brand", "kind"]:
        response = requests.post(
            domain_url + "/api/store/find/%s/%s" % (ftype, arg),
            verify=False
        )

        data = response.json()
        SearchResultsSchema().load(data)
        assert response.status_code == 200
        assert data["total"] == 5

    response = requests.post(
        domain_url + "/api/store/find/search/%s" % (arg),
        verify=False
    )

    data = response.json()
    SearchResultsSchema().load(data)
    assert response.status_code == 200
    assert data["total"] == 10

    for ftype in ["brand", "kind"]:
        response = requests.post(
            domain_url + "/api/store/find/%s/%s" % (ftype, arg),
            json={
                "pricerange": {
                    "min": 1,
                    "max": 500
                }
            },
            verify=False
        )

        data = response.json()
        SearchResultsSchema().load(data)
        assert response.status_code == 200
        assert data["total"] == 5

    response = requests.post(
        domain_url + "/api/store/find/search/%s" % (arg),
        json={
            "pricerange": {
                "min": 1,
                "max": 500
            }
        },
        verify=False
    )

    data = response.json()
    SearchResultsSchema().load(data)
    assert response.status_code == 200
    assert data["total"] == 10

    for ftype in ["brand", "kind"]:
        response = requests.post(
            domain_url + "/api/store/find/%s/%s" % (ftype, arg),
            json={
                "pricerange": {
                    "min": 10000,
                    "max": 20000
                }
            },
            verify=False
        )

        with pytest.raises(JSONDecodeError):
            response.json()

        assert response.status_code == 204

    response = requests.post(
        domain_url + "/api/store/find/search/%s" % (arg),
        json={
            "pricerange": {
                "min": 10000,
                "max": 20000
            }
        },
        verify=False
    )

    with pytest.raises(JSONDecodeError):
        response.json()

    assert response.status_code == 204

    for ftype in ["brand", "kind"]:
        response = requests.post(
            domain_url + "/api/store/find/%s/%s" % (ftype, str(uuid4())),
            verify=False
        )

        with pytest.raises(JSONDecodeError):
            response.json()

        assert response.status_code == 204

    response = requests.post(
        domain_url + "/api/store/find/search/%s" % (str(uuid4())),
        verify=False
    )

    with pytest.raises(JSONDecodeError):
        response.json()

    assert response.status_code == 204


text:
"""
Defines tools for testing.

- The :func:`make_docs_suite` function to automatically run :cmd:`doctest` on each document of a doctree.
- an extended TestCase with methods to launch a subprocess.

"""

import os
from os.path import join, pathsep
import unittest
import glob
from fnmatch import fnmatch
import sys
from setuptools import find_packages
# from pathlib import Path
import subprocess

from atelier.utils import SubProcessParent

DOCTEST_CMD = "doctest"

def interpreter_args():
    # if 'coverage' in sys.modules:
    #     # raise Exception('20160119')
    #     return ['coverage', 'run']
    return [sys.executable]

class DocTestCase(unittest.FunctionTestCase, SubProcessParent):
    # internally used by make_docs_suite

    def __init__(self, filename, addenv=None):
        self.addenv = addenv
        def func():
            args = [sys.executable]
            args += ["-m"]
            args += [DOCTEST_CMD]
            args += [filename]
            self.run_subprocess(args)
        func.__name__ = filename
        super(DocTestCase, self).__init__(func)

    def build_environment(self):
        env = super(DocTestCase, self).build_environment()
        env.pop('PYTHONPATH', None)  # fixes #1296
        if self.addenv is not None:
            env.update(self.addenv)
        return env

def make_docs_suite(docs_root, include="*.rst", exclude=None,
                    addenv=None):
    """
    Discover the doc files in specified directory docs_root and below
    and return a test suite which tests them all, each one in a
    separate subprocess.

    `include` is a filename pattern of the files to include. Default
    is `'*.rst'`.

    `exclude` is an optional filename pattern of the files to exclude. It can be
    a `str` with a single pattern or multiple patterns separated by `:`, or an
    iterator that yields patterns. If a filename matches any of the patterns, it
    will be skipped. Default value is None.

    `addenv` is an optional dictionary with additional environment
    variables to be set in the subprocess. Default is None.

    The tests are sorted alphabeticallly in order to avoid surprises
    when some doctest inadvertantly modifies the database.
    """
    suite = unittest.TestSuite()
    count = 0
    if exclude is None:
        exclude_patterns = []
    elif isinstance(exclude, str):
        exclude_patterns = exclude.split(pathsep)
    else:
        exclude_patterns = exclude

    def match_exclude(fn):
        for pat in exclude_patterns:
            if fnmatch(fn, pat):
                return True
        return False

    for root, dirs, files in os.walk(docs_root):
        dirs.sort()
        for file in sorted(files):
            fn = join(root, file)
            if fnmatch(fn, include):
                if match_exclude(fn):
                    print("Skip doctest for {}".format(fn))
                    continue
                suite.addTest(DocTestCase(fn, addenv))
                count += 1
    print("Loaded {} doctests from {}".format(count, docs_root))
    return suite

class TestCase(unittest.TestCase, SubProcessParent):
    "A unittest testcase with some additional utility methods."

    project_root = NotImplementedError
    # maxDiff = None

    def run_packages_test(self, declared_packages):
        """
        Checks whether the `packages` parameter to setup seems correct, i.e.
        whether all packages in the repository are being published in a source
        distribution.  This is kind of basic hygiene because you usually forget
        to update this parameter when you add or remove a package.

        """
        found_packages = find_packages()
        # if tests exists, remove it:
        if 'tests' in found_packages:
            found_packages.remove('tests')
        found_packages.sort()
        declared_packages.sort()
        self.assertEqual(found_packages, declared_packages)

    def run_simple_doctests(self, filenames, **kw):  # env.simple_doctests
        """
        run doctest of given file in a subprocess
        """
        for ln in filenames.splitlines():
            ln = ln.strip()
            if ln and not ln.startswith('#'):
                ok = False
                for fn in glob.glob(ln):
                    ok = True
                    args = interpreter_args()
                    args += ["-m"]
                    # args += ["doctest"]
                    args += [DOCTEST_CMD]
                    args += [fn]
                    self.run_subprocess(args, **kw)
                if not ok:
                    self.fail("no files matching %s" % ln)

    def run_unittest(self, filename, **kw):
        """
        run unittest of given file in a subprocess
        """
        args = interpreter_args()
        #~ args += ["-Wall"]
        args += ["-m"]
        args += ["unittest"]
        #~ args += ["--buffer"]
        args += [filename]
        self.run_subprocess(args, **kw)


text:
using System;
using System.Linq.Expressions;
using System.Reflection;
using Mozlite.Core;
using Mozlite.Properties;

namespace Mozlite.Data.Metadata.Internal
{
    /// <summary>
    /// 属性获取工厂类。
    /// </summary>
    public class ClrPropertyGetterFactory : ClrAccessorFactory<IClrPropertyGetter>
    {
        /// <summary>
        /// 创建当前访问器实例。
        /// </summary>
        /// <typeparam name="TEntity">当前实体类型。</typeparam>
        /// <typeparam name="TValue">属性的CLR类型。</typeparam>
        /// <typeparam name="TNonNullableEnumValue">此属性的基础类型。</typeparam>
        /// <param name="propertyInfo">属性信息实例。</param>
        /// <returns>返回当前属性的访问器实例。</returns>
        protected override IClrPropertyGetter CreateGeneric<TEntity, TValue, TNonNullableEnumValue>(PropertyInfo propertyInfo)
        {
            var memberInfo = propertyInfo.FindGetterProperty();

            if (memberInfo == null)
            {
                throw new InvalidOperationException(string.Format(
                    Resources.NoGetter, propertyInfo.Name, propertyInfo.DeclaringType.DisplayName(false)));
            }

            var entityParameter = Expression.Parameter(typeof(TEntity), "entity");

            return new ClrPropertyGetter<TEntity, TValue>(Expression.Lambda<Func<TEntity, TValue>>(
                Expression.MakeMemberAccess(entityParameter, memberInfo),
                entityParameter).Compile());
        }
    }
}


text:
package ch.idsia.tools;

import ch.idsia.benchmark.mario.engine.sprites.Sprite;

import java.util.HashSet;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by IntelliJ IDEA.
 * User: Sergey Karakovskiy, sergey.karakovskiy@gmail.com
 * Date: Sep 17, 2010
 * Time: 1:38:10 AM
 * Package: ch.idsia.tools
 */
public class RandomCreatureGenerator extends Random
{

    private HashSet<String> allowedCreatures = new HashSet<String>();
    private boolean creaturesEnabled = true;
    private boolean kindByDifficulty = true;
    private int difficulty = 0;
    private final String[] kinds = {"g", "gw", "gk", "gkw", "rk", "rkw", "s", "sw", "gww"};
    private String lastDecreased;

    private final int INFINITE = -1;

    private int GOOMBA = 0;
    private int GOOMBA_WINGED = 1;
    private int RED_KOOPA = 2;
    private int RED_KOOPA_WINGED = 3;
    private int GREEN_KOOPA = 4;
    private int GREEN_KOOPA_WINGED = 5;
    private int SPIKY = 6;
    private int SPIKY_WINGED = 7;
    private int WAVE_GOOMBA = 7;

    private int[] counters = new int[9];

    public RandomCreatureGenerator(long seed, String creatures, int difficulty)
    {
        super(seed);
        this.setSeed(seed, creatures, difficulty);
    }

    public void setSeed(long seed, String creatures, int difficulty)
    {
        this.setSeed(seed);
        this.difficulty = difficulty;

        if (creatures.equals("off"))
        {
            creaturesEnabled = false;
        }
        else
        {
            creaturesEnabled = true;

            if (!creatures.equals(""))
            {
                kindByDifficulty = false;
                Pattern pattern = Pattern.compile("[gsfr]k?w?w?(:\\d+)?");
                Matcher matcher = pattern.matcher(creatures);

                while (matcher.find())
                {
                    String group = matcher.group();
                    String[] subgroups = group.split(":");
                    allowedCreatures.add(subgroups[0]);
                    int index = getCreatureIndex(subgroups[0]);
                    if (subgroups.length == 2)
                    {
                        int count = Integer.valueOf(subgroups[1]);
                        counters[index] = count;
                    }
                    else
                    {
                        counters[index] = Integer.MAX_VALUE;
                    }
                    //TODO:[M] handle gw:0 situation
                    //TODO:|L| creatures type depends on difficulty, but number of creatures can be specified for each kind of creature.
                }
            }
            else
            {
                kindByDifficulty = true;
            }
        }
        //    System.out.println(allowedCreatures.toString());
    }

    public boolean canAdd()
    {
        return creaturesEnabled;
    }

    private int getCreatureType(String type)
    {
        int kind = Sprite.KIND_UNDEF;
        try
        {
            switch (type.charAt(0))
            {
                case 'g':
                    kind = Sprite.KIND_GOOMBA;
                    if (type.charAt(1) == 'w')
                    {
                        kind = Sprite.KIND_GOOMBA_WINGED;
                        if (type.charAt(2) == 'w')
                        {
                            kind = Sprite.KIND_WAVE_GOOMBA;
                        }
                    }
                    else if (type.charAt(1) == 'k')
                    {
                        kind = Sprite.KIND_GREEN_KOOPA;
                        if (type.charAt(2) == 'w')
                        {
                            kind = Sprite.KIND_GREEN_KOOPA_WINGED;
                        }
                    }
                    break;
                case 'r':
                    kind = Sprite.KIND_RED_KOOPA;
                    if (type.charAt(2) == 'w')
                    {
                        kind = Sprite.KIND_RED_KOOPA_WINGED;
                    }
                    break;
                case 's':
                    kind = Sprite.KIND_SPIKY;
                    if (type.charAt(1) == 'w')
                    {
                        kind = Sprite.KIND_SPIKY_WINGED;
                    }
                    break;
            }
        }
        catch (Exception e)
        {
            return kind;
        }

        return kind;
    }

    private int getCreatureIndex(String c)
    {
        if (c.equals("g"))
        {
            return GOOMBA;
        }
        if (c.equals("gw"))
        {
            return GOOMBA_WINGED;
        }
        if (c.equals("gk"))
        {
            return GREEN_KOOPA;
        }
        if (c.equals("gkw"))
        {
            return GREEN_KOOPA_WINGED;
        }
        if (c.equals("rk"))
        {
            return RED_KOOPA;
        }
        if (c.equals("rkw"))
        {
            return RED_KOOPA_WINGED;
        }
        if (c.equals("s"))
        {
            return SPIKY;
        }
        if (c.equals("sw"))
        {
            return SPIKY_WINGED;
        }
        if (c.equals("gww"))
        {
            return WAVE_GOOMBA;
        }

        throw new ArrayStoreException("Unknown kind of the creature: " + c);
    }

    private void decreaseCreatureCounter(String c)
    {
        lastDecreased = c;

        int left = --counters[getCreatureIndex(c)];

        if (left == 0)
        {
            allowedCreatures.remove(c);
        }
    }

    public int nextCreature()
    {
        int kind = Sprite.KIND_UNDEF;

        if (allowedCreatures.size() == 0 && !kindByDifficulty)
        {
            return kind;
        }

        if (kindByDifficulty)
        {
            kind = getCreatureType(kinds[this.nextInt(9)]);
            if (difficulty < 1)
            {
                kind = this.getCreatureType("g");
            }
            else if (difficulty < 3)
            {
                String type = kinds[this.nextInt(6)];
                kind = this.getCreatureType(type);
            }
        }
        else
        {
            Object[] localKinds = allowedCreatures.toArray();
            String c = (String) localKinds[this.nextInt(localKinds.length)];
            kind = this.getCreatureType(c);
            decreaseCreatureCounter(c);
        }

        return kind;
    }

    public void increaseLastCreature()
    {
        if (!kindByDifficulty)
        {
            int index = getCreatureIndex(lastDecreased);
            if (counters[index] == 0)
            {
                allowedCreatures.add(lastDecreased);
            }
            ++counters[index];
        }
    }

    public boolean isCreatureEnabled(String creature)
    {
        return creature.equals("f") || allowedCreatures.contains(creature);
    }
}


text:
<?php

/**
 * Created by HKM Corporation.
 * User: Hesk
 * Date: 14年8月28日
 * Time: 上午11:34
 */
class SingleApp extends SingleBase
{
    protected $comment;

    /**
     * get an array of IDs from the stock count table according to $this->post_id (stock ID)
     */
    private function get_stock_row()
    {
        $this->stock_operation = new StockOperation();
        return $this->stock_operation->list_stock_data($this->post_id);
    }

    /**
     * @return array
     */
    public function list_reward_details()
    {
        return $this->content;
    }

    protected function isType($type)
    {
        return $type == APPDISPLAY;
    }

    /**
     * @return array
     */
    protected function queryobject()
    {
        $title = get_the_title($this->post_id);
        $icon_url = get_post_meta($this->post_id, "_icon", true);
        $store_id = get_post_meta($this->post_id, "_storeid", true);
        $description = get_post_meta($this->post_id, "_description", true);
        $platform = get_post_meta($this->post_id, "_platform", true);
        $developer_id = intval(get_post_meta($this->post_id, "_developer", true));
        $developer_name = get_post_meta($this->post_id, "_developer_name", true);
        $app_name = get_post_meta($this->post_id, "_appname", true);
        $app_key = get_post_meta($this->post_id, "_appkey", true);
        $coin = intval(get_post_meta($this->post_id, "price", true));
        $images_list_str = get_post_meta($this->post_id, "_screen_shot", true);
        $app_key = get_post_meta($this->post_id, "_appkey", true);
        $screenshot = $images_list_str == "" ? array() : explode(";_;", $images_list_str);
        /*
         *
        $image_banner = $this->get_product_image("inno_image_banner");

        $image_small_thumb = $this->get_product_image("inno_image_thumb");
        $image_video_cover = $this->get_product_image("inno_video_cover_image");*/
        $country = $platform == 'ios' ? $this->get_terms("countryios_nd") : $this->get_terms("countryandroid");
        $category = $platform == 'ios' ? $this->get_terms("appcate") : $this->get_terms("appandroid");
        $image_slider = $this->get_image_series("inno_image_slider");

        $this->app_comment = new AppComment($this->post_id);
        $comment = $this->app_comment->default_comment();
        $comment_count = $this->app_comment->get_count();
        $share_count = $this->app_comment->get_share_count();
        $download_count = intval(get_post_meta($this->post_id, "dl_count", true));

        unset($images_list_str);
        return get_defined_vars();
    }
}


text:
all: build
version=1.0.0
COMPILE=$(shell date -u "+%Y-%m-%d/%H:%M:%S")
build:
	go build -ldflags "-X github.com/lijiaocn/golib/version.VERSION=${version} -X github.com/lijiaocn/golib/version.COMPILE=${COMPILE}"


text:
import { testStorage } from "./test_utils.js";

import { Unlocker, UnlockCondition, UnlockByDefault } from "../src/gjs/unlocker.js";
import { StateSaver } from "../src/gjs/statesaver.js";

var testUnlockCondition = function() {
    var TestCondition = function(options) {
        this.initCondition(options);
    };

    TestCondition.prototype = new UnlockCondition();

    TestCondition.prototype.update = function(gameState, deltaTime) {
        if (gameState.unlocked) {
            this.fulfilled = true;
        }
    };

    return new TestCondition({unlockId: 'test'});
};

/**
 * @constructor
 */
var TestGameState = function() {
    this.unlocked = false;
};

describe('UnlockCondition', function() {
    it('initializes', function() {
        var condition = testUnlockCondition();
        expect(condition.unlockId).toBe('test');
        expect(condition.fulfilled).toBe(false);
    });

    it('initializes unlocked by default', function() {
        var condition = new UnlockByDefault({unlockId: 'foo'});
        expect(condition.unlockId).toBe('foo');
        expect(condition.fulfilled).toBe(true);
    });
});

describe('Unlocker', function() {
    it('initializes', function() {
        var unlocker = new Unlocker({
            needCommitUnlocks: true,
            conditions: [testUnlockCondition()]
        });
        expect(unlocker.needCommitUnlocks).toBe(true);
        expect(unlocker.unlocks['test']).toBe(false);
        expect(unlocker.saveState.unlocksInOrder.length).toBe(0);
    });

    it('initializes with something unlocked by default', function() {
        var unlocker = new Unlocker({
            needCommitUnlocks: false,
            conditions: [new UnlockByDefault({unlockId: 'foo'})]
        });
        expect(unlocker.needCommitUnlocks).toBe(false);
        expect(unlocker.unlocks['foo']).toBe(true);
        expect(unlocker.saveState.unlocksInOrder[0]).toBe('foo');
    });

    it('updates', function() {
        var gameState = new TestGameState();
        var unlocker = new Unlocker({
            needCommitUnlocks: false,
            conditions: [testUnlockCondition()]
        });
        unlocker.update(gameState, 1 / 60);
        expect(unlocker.unlocks['test']).toBe(false);
        expect(unlocker.saveState.unlocksInOrder.length).toBe(0);
        gameState.unlocked = true;
        unlocker.update(gameState, 1 / 60);
        expect(unlocker.unlocks['test']).toBe(true);
        expect(unlocker.saveState.unlocksInOrder[0]).toBe('test');
    });

    it('manually commits unlocks', function() {
        var gameState = new TestGameState();
        var unlocker = new Unlocker({
            needCommitUnlocks: true,
            conditions: [testUnlockCondition()]
        });
        gameState.unlocked = true;
        unlocker.update(gameState, 1 / 60);
        expect(unlocker.unlocks['test']).toBe(false);
        expect(unlocker.saveState.unlocksInOrder.length).toBe(0);
        expect(unlocker._fulfilledConditions.length).toBe(1);

        var fulfilled = unlocker.popFulfilledUnlockConditions();
        expect(fulfilled.length).toBe(1);
        expect(fulfilled[0]).toBe('test');
        expect(unlocker._fulfilledConditions.length).toBe(0);

        unlocker.commitUnlock('test');
        expect(unlocker.unlocks['test']).toBe(true);
        expect(unlocker.saveState.unlocksInOrder[0]).toBe('test');
    });

    it('loads from empty storage', function() {
        var unlocker = new Unlocker({
            needCommitUnlocks: false,
            conditions: [testUnlockCondition()]
        });

        var saver = new StateSaver({
            savedObjects: [unlocker]
        });

        var storage = testStorage();

        saver.loadFrom(storage);
        expect(unlocker.unlocks['test']).toBe(false);
        expect(unlocker.saveState.unlocksInOrder.length).toBe(0);
    });

    it('loads from storage with unlocks', function() {
        var unlockerA = new Unlocker({
            needCommitUnlocks: false,
            conditions: [testUnlockCondition()]
        });
        unlockerA.commitUnlock('test');

        var saverA = new StateSaver({
            savedObjects: [unlockerA]
        });

        var storage = testStorage();

        saverA.saveTo(storage);

        var unlockerB = new Unlocker({
            needCommitUnlocks: false,
            conditions: [testUnlockCondition()]
        });

        var saverB = new StateSaver({
            savedObjects: [unlockerB]
        });

        saverB.loadFrom(storage);
        expect(unlockerB.unlocks['test']).toBe(true);
        expect(unlockerB.saveState.unlocksInOrder[0]).toBe('test');
    });
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>org.aisen.android</groupId>
  <artifactId>aisen</artifactId>
  <version>1.0.0-SNAPSHOT</version>
  <versioning>
    <snapshot>
      <timestamp>20160407.161237</timestamp>
      <buildNumber>1</buildNumber>
    </snapshot>
    <lastUpdated>20160407161237</lastUpdated>
  </versioning>
</metadata>