text:
using ::testing::_;

namespace blink {

namespace {
const float kTestVolume = 0.25;
const int kTestSampleRate = 48000;
}  // namespace

class WebAudioSourceProviderImplTest : public testing::Test,
                                       public WebAudioSourceProviderClient {
 public:
  WebAudioSourceProviderImplTest()
      : params_(media::AudioParameters::AUDIO_PCM_LINEAR,
                media::CHANNEL_LAYOUT_STEREO,
                kTestSampleRate,
                64),
        fake_callback_(0.1, kTestSampleRate),
        mock_sink_(new media::MockAudioRendererSink()),
        wasp_impl_(new WebAudioSourceProviderImpl(mock_sink_, &media_log_)) {}

  virtual ~WebAudioSourceProviderImplTest() = default;

  void CallAllSinkMethodsAndVerify(bool verify) {
    testing::InSequence s;

    EXPECT_CALL(*mock_sink_, Start()).Times(verify);
    wasp_impl_->Start();

    EXPECT_CALL(*mock_sink_, Play()).Times(verify);
    wasp_impl_->Play();

    EXPECT_CALL(*mock_sink_, Pause()).Times(verify);
    wasp_impl_->Pause();

    EXPECT_CALL(*mock_sink_, SetVolume(kTestVolume)).Times(verify);
    wasp_impl_->SetVolume(kTestVolume);

    EXPECT_CALL(*mock_sink_, Stop()).Times(verify);
    wasp_impl_->Stop();

    testing::Mock::VerifyAndClear(mock_sink_.get());
  }

  void SetClient(WebAudioSourceProviderClient* client) {
    testing::InSequence s;

    if (client) {
      EXPECT_CALL(*mock_sink_, Stop());
      EXPECT_CALL(*this, SetFormat(params_.channels(), params_.sample_rate()));
    }
    wasp_impl_->SetClient(client);
    base::RunLoop().RunUntilIdle();

    testing::Mock::VerifyAndClear(mock_sink_.get());
    testing::Mock::VerifyAndClear(this);
  }

  bool CompareBusses(const media::AudioBus* bus1, const media::AudioBus* bus2) {
    EXPECT_EQ(bus1->channels(), bus2->channels());
    EXPECT_EQ(bus1->frames(), bus2->frames());
    for (int ch = 0; ch < bus1->channels(); ++ch) {
      if (memcmp(bus1->channel(ch), bus2->channel(ch),
                 sizeof(*bus1->channel(ch)) * bus1->frames()) != 0) {
        return false;
      }
    }
    return true;
  }

  // WebAudioSourceProviderClient implementation.
  MOCK_METHOD2(SetFormat, void(uint32_t numberOfChannels, float sampleRate));

  // CopyAudioCB. Added forwarder method due to GMock troubles with scoped_ptr.
  MOCK_METHOD3(DoCopyAudioCB,
               void(media::AudioBus*,
                    uint32_t frames_delayed,
                    int sample_rate));
  void OnAudioBus(std::unique_ptr<media::AudioBus> bus,
                  uint32_t frames_delayed,
                  int sample_rate) {
    DoCopyAudioCB(bus.get(), frames_delayed, sample_rate);
  }

  int Render(media::AudioBus* audio_bus) {
    return wasp_impl_->RenderForTesting(audio_bus);
  }

 protected:
  base::test::TaskEnvironment task_environment_;

  media::AudioParameters params_;
  media::FakeAudioRenderCallback fake_callback_;
  media::NullMediaLog media_log_;
  scoped_refptr<media::MockAudioRendererSink> mock_sink_;
  scoped_refptr<WebAudioSourceProviderImpl> wasp_impl_;

  DISALLOW_COPY_AND_ASSIGN(WebAudioSourceProviderImplTest);
};

TEST_F(WebAudioSourceProviderImplTest, SetClientBeforeInitialize) {
  // setClient() with a nullptr client should do nothing if no client is set.
  wasp_impl_->SetClient(nullptr);

  // If |mock_sink_| is not null, it should be stopped during setClient(this).
  if (mock_sink_)
    EXPECT_CALL(*mock_sink_.get(), Stop());

  wasp_impl_->SetClient(this);
  base::RunLoop().RunUntilIdle();

  wasp_impl_->SetClient(nullptr);
  base::RunLoop().RunUntilIdle();

  wasp_impl_->SetClient(this);
  base::RunLoop().RunUntilIdle();

  // When Initialize() is called after setClient(), the params should propagate
  // to the client via setFormat() during the call.
  EXPECT_CALL(*this, SetFormat(params_.channels(), params_.sample_rate()));
  wasp_impl_->Initialize(params_, &fake_callback_);
  base::RunLoop().RunUntilIdle();

  // setClient() with the same client should do nothing.
  wasp_impl_->SetClient(this);
  base::RunLoop().RunUntilIdle();
}

// Verify AudioRendererSink functionality w/ and w/o a client.
TEST_F(WebAudioSourceProviderImplTest, SinkMethods) {
  wasp_impl_->Initialize(params_, &fake_callback_);

  // Without a client all WASP calls should fall through to the underlying sink.
  CallAllSinkMethodsAndVerify(true);

  // With a client no calls should reach the Stop()'d sink.  Also, setClient()
  // should propagate the params provided during Initialize() at call time.
  SetClient(this);
  CallAllSinkMethodsAndVerify(false);

  // Removing the client should cause WASP to revert to the underlying sink;
  // this shouldn't crash, but shouldn't do anything either.
  SetClient(nullptr);
  CallAllSinkMethodsAndVerify(false);
}

// Test the AudioRendererSink state machine and its effects on provideInput().
TEST_F(WebAudioSourceProviderImplTest, ProvideInput) {
  auto bus1 = media::AudioBus::Create(params_);
  auto bus2 = media::AudioBus::Create(params_);

  // Point the WebVector into memory owned by |bus1|.
  WebVector<float*> audio_data(static_cast<size_t>(bus1->channels()));
  for (size_t i = 0; i < audio_data.size(); ++i)
    audio_data[i] = bus1->channel(static_cast<int>(i));

  // Verify provideInput() works before Initialize() and returns silence.
  bus1->channel(0)[0] = 1;
  bus2->Zero();
  wasp_impl_->ProvideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));

  wasp_impl_->Initialize(params_, &fake_callback_);
  SetClient(this);

  // Verify provideInput() is muted prior to Start() and no calls to the render
  // callback have occurred.
  bus1->channel(0)[0] = 1;
  bus2->Zero();
  wasp_impl_->ProvideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));
  ASSERT_EQ(fake_callback_.last_delay(), base::TimeDelta::Max());

  wasp_impl_->Start();

  // Ditto for Play().
  bus1->channel(0)[0] = 1;
  wasp_impl_->ProvideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));
  ASSERT_EQ(fake_callback_.last_delay(), base::TimeDelta::Max());

  wasp_impl_->Play();

  // Now we should get real audio data.
  wasp_impl_->ProvideInput(audio_data, params_.frames_per_buffer());
  ASSERT_FALSE(CompareBusses(bus1.get(), bus2.get()));

  // Ensure volume adjustment is working.
  fake_callback_.reset();
  fake_callback_.Render(base::TimeDelta(), base::TimeTicks::Now(), 0,
                        bus2.get());
  bus2->Scale(kTestVolume);

  fake_callback_.reset();
  wasp_impl_->SetVolume(kTestVolume);
  wasp_impl_->ProvideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));

  // Pause should return to silence.
  wasp_impl_->Pause();
  bus1->channel(0)[0] = 1;
  bus2->Zero();
  wasp_impl_->ProvideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));

  // Ensure if a renderer properly fill silence for partial Render() calls by
  // configuring the fake callback to return half the data.  After these calls
  // bus1 is full of junk data, and bus2 is partially filled.
  wasp_impl_->SetVolume(1);
  fake_callback_.Render(base::TimeDelta(), base::TimeTicks::Now(), 0,
                        bus1.get());
  fake_callback_.reset();
  fake_callback_.Render(base::TimeDelta(), base::TimeTicks::Now(), 0,
                        bus2.get());
  bus2->ZeroFramesPartial(bus2->frames() / 2,
                          bus2->frames() - bus2->frames() / 2);
  fake_callback_.reset();
  fake_callback_.set_half_fill(true);
  wasp_impl_->Play();

  // Play should return real audio data again, but the last half should be zero.
  wasp_impl_->ProvideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));

  // Stop() should return silence.
  wasp_impl_->Stop();
  bus1->channel(0)[0] = 1;
  bus2->Zero();
  wasp_impl_->ProvideInput(audio_data, params_.frames_per_buffer());
  ASSERT_TRUE(CompareBusses(bus1.get(), bus2.get()));
}

// Verify CopyAudioCB is called if registered.
TEST_F(WebAudioSourceProviderImplTest, CopyAudioCB) {
  testing::InSequence s;
  wasp_impl_->Initialize(params_, &fake_callback_);
  wasp_impl_->SetCopyAudioCallback(WTF::BindRepeating(
      &WebAudioSourceProviderImplTest::OnAudioBus, base::Unretained(this)));

  const auto bus1 = media::AudioBus::Create(params_);
  EXPECT_CALL(*this, DoCopyAudioCB(_, 0, params_.sample_rate())).Times(1);
  Render(bus1.get());

  wasp_impl_->ClearCopyAudioCallback();
  EXPECT_CALL(*this, DoCopyAudioCB(_, _, _)).Times(0);
  Render(bus1.get());

  testing::Mock::VerifyAndClear(mock_sink_.get());
}

TEST_F(WebAudioSourceProviderImplTest, MultipleInitializeWithSetClient) {
  // setClient() with a nullptr client should do nothing if no client is set.
  wasp_impl_->SetClient(nullptr);

  // When Initialize() is called after setClient(), the params should propagate
  // to the client via setFormat() during the call.
  EXPECT_TRUE(wasp_impl_->IsOptimizedForHardwareParameters());
  EXPECT_CALL(*this, SetFormat(params_.channels(), params_.sample_rate()));
  wasp_impl_->Initialize(params_, &fake_callback_);
  base::RunLoop().RunUntilIdle();

  // If |mock_sink_| is not null, it should be stopped during setClient(this).
  if (mock_sink_)
    EXPECT_CALL(*mock_sink_.get(), Stop());

  // setClient() with the same client should do nothing.
  wasp_impl_->SetClient(this);
  base::RunLoop().RunUntilIdle();

  // Stop allows Initialize() to be called again.
  wasp_impl_->Stop();

  // It's possible that due to media change or just the change in the return
  // value for IsOptimizedForHardwareParameters() that different params are
  // given. Ensure this doesn't crash.
  EXPECT_FALSE(wasp_impl_->IsOptimizedForHardwareParameters());
  auto stream_params = media::AudioParameters(
      media::AudioParameters::AUDIO_PCM_LINEAR, media::CHANNEL_LAYOUT_MONO,
      kTestSampleRate * 2, 64);

  EXPECT_CALL(*this,
              SetFormat(stream_params.channels(), stream_params.sample_rate()));
  wasp_impl_->Initialize(stream_params, &fake_callback_);
  base::RunLoop().RunUntilIdle();

  wasp_impl_->Start();
  wasp_impl_->Play();

  auto bus1 = media::AudioBus::Create(stream_params);
  auto bus2 = media::AudioBus::Create(stream_params);

  // Point the WebVector into memory owned by |bus1|.
  WebVector<float*> audio_data(static_cast<size_t>(bus1->channels()));
  for (size_t i = 0; i < audio_data.size(); ++i)
    audio_data[i] = bus1->channel(static_cast<int>(i));

  // Verify provideInput() doesn't return silence and doesn't crash.
  bus1->channel(0)[0] = 1;
  bus2->Zero();
  wasp_impl_->ProvideInput(audio_data, params_.frames_per_buffer());
  ASSERT_FALSE(CompareBusses(bus1.get(), bus2.get()));
}

}  // namespace blink

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Crm\VentasBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class VentaType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('fechaVenta','date',array('widget'=>'single_text'))
            ->add('usuarios')
            ->add('noDisponible',null,array("required" => false))
            ->add('estatus','choice',array('choices' => array('Demo' => 'Demo','Venta' => 'Venta'),'attr' => array('class' => 'form-control')))
            ->add('termino')
            ->add('cliente')
            ->add('equipo','entity', array(
                'class' => 'EquipoBundle:Equipo',
                'property' => 'serieWarriors',
                'query_builder' => function (\Crm\EquipoBundle\Entity\EquipoRepository $repository){
                    return $repository->createQueryBuilder('equipo')
                    ->orderBy('equipo.checkVenta', 'ASC')
                    ->where('equipo.checkVenta = :check')
                    ->setParameter('check', 'f');}
                ))
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Crm\VentasBundle\Entity\Venta'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'crm_ventasbundle_venta';
    }
}


text:
package org.apache.webbeans.test.concepts.vetoes;

import org.apache.webbeans.test.AbstractUnitTest;
import org.apache.webbeans.test.concepts.vetoes.vetoedpackage.subpackage.VetoedBean;
import org.junit.Assert;
import org.junit.Test;

import javax.enterprise.inject.spi.Bean;

public class VetoedPackageTest  extends AbstractUnitTest
{
    @Test
    public void testVetoPackageLevel()
    {
        startContainer(VetoedBean.class);

        Bean<VetoedBean> vetoedBean = getBean(VetoedBean.class);
        Assert.assertNull(vetoedBean);
    }

    @Test
    public void skipVetoedOnpackage()
    {
        addConfiguration("org.apache.webbeans.spi.deployer.skipVetoedOnPackages", "true");
        startContainer(VetoedBean.class);

        Bean<VetoedBean> vetoedBean = getBean(VetoedBean.class);
        Assert.assertNotNull(vetoedBean);
    }
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.5"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Vulkan Memory Allocator: File Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Vulkan Memory Allocator

Loading...

Searching...

No Matches

VmaAllocationCreateFlagBits : vk_mem_alloc.h

VmaAllocatorCreateFlagBits : vk_mem_alloc.h

VmaDefragmentationFlagBits : vk_mem_alloc.h

VmaDefragmentationMoveOperation : vk_mem_alloc.h

VmaMemoryUsage : vk_mem_alloc.h

VmaPoolCreateFlagBits : vk_mem_alloc.h

VmaVirtualAllocationCreateFlagBits : vk_mem_alloc.h

VmaVirtualBlockCreateFlagBits : vk_mem_alloc.h

<address class="footer">
Generated by  1.9.5
</address>


text:
from functools import wraps
import hashlib

from google.appengine.api import urlfetch

from django.core.urlresolvers import reverse
from django.http import Http404, HttpResponseRedirect
from django.utils import simplejson
from django.utils.http import urlencode

from app import config
from app.models import User

## Decorators

def ajax_method(FormClass=None, method='POST', attach_user=True):
    def decorator(view_func):
        def _ajax_method(request, *args, **kwargs):
            # NOTE: uncomment the following two lines if you would like to test
            # AJAX calls in the browser (as GET requests instead of POST)
            # On production these should be activated to prevent spoofing
            if request.method != method and method != 'REQUEST': raise Http404('Request must be a ' + method)
            if not request.is_ajax(): raise Http404('Request must be AJAX')
            if FormClass:
                f = FormClass(getattr(request, method))
                if not f.is_valid(): raise Http404('Invalid form', f.errors.as_text())
                request.form = f
            if attach_user:
                request.user = get_user(request)
            return view_func(request, *args, **kwargs)
        return wraps(view_func)(_ajax_method)
    return decorator

def login_required(view_func):
    def _login_required(request, *args, **kwargs):
        auth_token = get_auth_token(request)
        if not auth_token:
            params = []
            if request.path != reverse('home'): params.extend(non_hunch_params(request))
            params.append(('next', top_url_from_request(request)))
            return HttpResponseRedirect(reverse('authorize') + '?' + urlencode(params))
        user = get_user(request)
        request.auth_token = auth_token
        request.user = user
        return view_func(request, *args, **kwargs)
    return wraps(view_func)(_login_required)

## Top Url function
def non_hunch_params(request):
    params = []
    for k,vs in request.GET.lists():
        if not k.startswith('hn_'):
            for v in vs:
                params.append((k, v))
    return params

_DEFAULT_ADD_HOST = True

def top_url_from_request(request, add_host=_DEFAULT_ADD_HOST):
    """
    Converts the current path into a top level path
    """
    return _top_url(request.path, request=request, add_host=add_host)

def top_url_from_str(app_url, add_host=_DEFAULT_ADD_HOST): #TODO(peter) - make this strip out query string arguments like the request variation does
    """
    Converts the given app url into a top level path
    """
    return _top_url(app_url, add_host=add_host)

def top_url(request, add_host=_DEFAULT_ADD_HOST):
    """
    Determines if request is a url or a request object and
    calls the appropriate top_url_FOO function.
    """
    if isinstance(request, (str, unicode)):
        app_url = request
        request = None
    else:
        app_url = request.path
    return _top_url(app_url, request=request, add_host=add_host)

## ...helper

def _top_url(app_url, request=None, add_host=_DEFAULT_ADD_HOST):
    home_url = reverse('home')

    if app_url.startswith(home_url):
        app_url = app_url[len(home_url):]

    if request and request.GET:
        params = non_hunch_params(request)
        if params: app_url += '?' + urlencode(params)

    return (config.HOSTNAME_PATH if add_host else '') + app_url #TODO(peter) - change the alan_parsons part when we update on production

## User functions
def get_auth_token(request):
    user_id = get_user_id(request)
    if not user_id:
        return False
    user = User.get_by_key_name(user_id)
    if not user or not user.auth_token:
        return False
    auth_token = user.auth_token
    params = {'app_id': config.APP_ID,
              'token': auth_token}
    params.update({'auth_sig': sign_request(params)})
    status = make_api_request(config.CHECK_AUTH_TOKEN_API_URL, params)

    if not status:
        return False
    status = status.get('status')
    if status == 'rejected':
        user.auth_token = ''
        user.auth_token_key = ''
        user.put()
        return False
    if status == 'accepted':
        return auth_token
    return False

def get_user(request):
    user_id = get_user_id(request)
    if not user_id: return None
    return User.get_by_key_name(user_id)

def get_user_id(request):
    return request.REQUEST.get('hn_user_id')

def get_topic_ids(user, blocked=False):
    user_is_male = is_male(user)
    if user_is_male == None:
        if blocked:
            return None, None
        return None
    elif user_is_male:
        # male
        if blocked:
            return config.MALE_TOPIC_IDS, config.FEMALE_TOPIC_IDS
        return config.MALE_TOPIC_IDS
    else:
        # female
        if blocked:
            return config.FEMALE_TOPIC_IDS, config.MALE_TOPIC_IDS
        return config.FEMALE_TOPIC_IDS

def is_male(user):
    response = user.thayresponse_set\
        .filter('question_id =', 'hn_424023')\
        .get()
    if not response:
        return None
        # response = make_api_request(config.AUTH_TOKEN_API_URL, params)
        # if not response:
            # # TODO(gleitz): something more intelligent that assuming you are female?
        # make_api_request()
    elif response.response_id == 'hn_1532633':
        return True
    elif response.response_id == 'hn_1532643':
        return False
    # TODO(gleitz): guess here?
    return None

def redirect_to_answer(request):
    return HttpResponseRedirect(reverse('answer') + '?' + request.GET.urlencode())

## Request functions

def make_api_request(url, params=None):
    params = params or {}
    request_url = url + '?' + urlencode(params)

    # if 'results' in request_url:
        # raise Exception(request_url)
    content = urlfetch.fetch(request_url, deadline=10)
    if content: content = content.content
    try:
        return simplejson.loads(content)
    except simplejson.JSONDecodeError, e:
        raise Exception('JSONDecodeError', url, content, e)

def sign_request(dict_object):
    encoded_args = sorted([(k.encode('utf-8') if type(k) in [str,unicode] else k, v.encode('utf-8') if type(v) in [str,unicode] else v) for k, v in dict_object.items()])
    sig = urlencode(encoded_args)
    sig += config.APP_SECRET
    return hashlib.sha1(sig).hexdigest()


text:
import React from 'react';
import { Image } from 'react-native';
import { StackNavigator } from 'react-navigation';
import ListContact from '../screens/authorized/home/contact/ListContact';
import Conversation from '../screens/authorized/home/contact/Conversation';

const TabContact = StackNavigator({
    List: {
        screen: ListContact,
        navigationOptions: {
            tabBar: {
                label: 'Contact',
                icon: ({ tintColor }) => <Image source={require('../img/icons/contact.png')} style={[styles.icon, { tintColor }]} />,
            }
        }
    },
    Conversation: { screen: Conversation },
});
const styles = {
    icon: {
        width: 32,
        height: 32
    }
};
export default TabContact;


text:
'use strict';

var _ = require('lodash');
var Promise = require('bluebird');
var requireDir = require('require-dir');
var services = requireDir('../services');

// Index
module.exports.index = function(req, res) {
  services.trials.getMapped().then(function(data) {
    res.render('index.html', {
      title: 'Ebola',
      subtitle: 'A live tracker of Ebola trials',
      trials: data,
      info: services.utils.collectTrialsInfo(data),
      req: req,
      disableLeaderboard: !!req.app.get('config').get('disable:leaderboard')
    });
  });
};

module.exports.chart = function(req, res) {
  var promises = [
    services.trials.getMapped(),
    services.cases.getMapped()
  ];
  Promise.all(promises).then(function(data) {
    var trials = data[0];
    var cases = data[1];
    var chartData = services.utils.collectDataForChart(trials, cases);
    res.render('graph.html', {
      title: 'Ebola Graph',
      chartData: JSON.stringify(chartData)
    });
  });
};


text:
if [ ! -f 'setup.py' -o ! -d 'anchore' ]; then
    echo "Looks like you are not running this from the root anchore code checkout - go there and try again (cd /path/to/checkout/of/anchore; ./scripts/release/make-rpm.sh)"
    exit 1
fi

REL=$1

if [ -z "$REL" ]; then
    echo "Need to pass a release number as parameter to this script"
    exit 1
fi

python setup.py bdist_rpm --requires="python python-setuptools python2-clint PyYAML python-requests python-click python-prettytable python-docker-py dpkg rpm-python python-jsonschema" --build-requires="python python-setuptools python-jsonschema" --release="$REL"
python setup.py clean --all


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

<view class="rootClass">
    <label property="label1" class="label1"/>
    <button property="button1" class="button1"/>
    <collectionView property="collectionView" layoutClass="CustomCollectionViewLayout"/>

    <uiview id="CustomView1Id" property="CustomView1Property" prototype="prototype1" prototypeScope="global" class="prototype1" impl="CustomView1" customAttr1="customValue1">
        <label property="label2" class="label2"/>

        <uiview class="nestedView2" property="customView2" impl="CustomView2">
            <label property="label3" class="label3"/>

            <view class="nestedView3" property="customView3">
                <label property="label4" class="label4"/>
                <label property="label5" class="label5"/>
            </view>

        </uiview>

    </uiview>

    <UICollectionView/>
    <UITableView/>

</view>


text:
#define IN_LIBXML
#include "libxml.h"
#include <stdlib.h>
#include <string.h>
#include <libxml/xmlmemory.h>
#include <libxml/tree.h>
#include <libxml/parser.h>
#include <libxml/parserInternals.h>
#include <libxml/valid.h>
#include <libxml/entities.h>
#include <libxml/xmlerror.h>
#include <libxml/debugXML.h>
#include <libxml/xmlIO.h>
#include <libxml/SAX.h>
#include <libxml/uri.h>
#include <libxml/valid.h>
#include <libxml/HTMLtree.h>
#include <libxml/globals.h>
#include <libxml/SAX2.h>

#ifdef LIBXML_LEGACY_ENABLED
#ifdef LIBXML_SAX1_ENABLED
/**
 * initxmlDefaultSAXHandler:
 * @hdlr:  the SAX handler
 * @warning:  flag if non-zero sets the handler warning procedure
 *
 * Initialize the default XML SAX version 1 handler
 * DEPRECATED: use xmlSAX2InitDefaultSAXHandler() for the new SAX2 blocks
 */
void
initxmlDefaultSAXHandler(xmlSAXHandlerV1* hdlr, int warning)
{
    if (hdlr->initialized == 1)
        return;

    hdlr->internalSubset = xmlSAX2InternalSubset;
    hdlr->externalSubset = xmlSAX2ExternalSubset;
    hdlr->isStandalone = xmlSAX2IsStandalone;
    hdlr->hasInternalSubset = xmlSAX2HasInternalSubset;
    hdlr->hasExternalSubset = xmlSAX2HasExternalSubset;
    hdlr->resolveEntity = xmlSAX2ResolveEntity;
    hdlr->getEntity = xmlSAX2GetEntity;
    hdlr->getParameterEntity = xmlSAX2GetParameterEntity;
    hdlr->entityDecl = xmlSAX2EntityDecl;
    hdlr->attributeDecl = xmlSAX2AttributeDecl;
    hdlr->elementDecl = xmlSAX2ElementDecl;
    hdlr->notationDecl = xmlSAX2NotationDecl;
    hdlr->unparsedEntityDecl = xmlSAX2UnparsedEntityDecl;
    hdlr->setDocumentLocator = xmlSAX2SetDocumentLocator;
    hdlr->startDocument = xmlSAX2StartDocument;
    hdlr->endDocument = xmlSAX2EndDocument;
    hdlr->startElement = xmlSAX2StartElement;
    hdlr->endElement = xmlSAX2EndElement;
    hdlr->reference = xmlSAX2Reference;
    hdlr->characters = xmlSAX2Characters;
    hdlr->cdataBlock = xmlSAX2CDataBlock;
    hdlr->ignorableWhitespace = xmlSAX2Characters;
    hdlr->processingInstruction = xmlSAX2ProcessingInstruction;
    if (warning == 0)
        hdlr->warning = NULL;
    else
        hdlr->warning = xmlParserWarning;
    hdlr->error = xmlParserError;
    hdlr->fatalError = xmlParserError;

    hdlr->initialized = 1;
}

#ifdef LIBXML_HTML_ENABLED

/**
 * inithtmlDefaultSAXHandler:
 * @hdlr:  the SAX handler
 *
 * Initialize the default HTML SAX version 1 handler
 * DEPRECATED: use xmlSAX2InitHtmlDefaultSAXHandler() for the new SAX2 blocks
 */
void
inithtmlDefaultSAXHandler(xmlSAXHandlerV1* hdlr)
{
    if (hdlr->initialized == 1)
        return;

    hdlr->internalSubset = xmlSAX2InternalSubset;
    hdlr->externalSubset = NULL;
    hdlr->isStandalone = NULL;
    hdlr->hasInternalSubset = NULL;
    hdlr->hasExternalSubset = NULL;
    hdlr->resolveEntity = NULL;
    hdlr->getEntity = xmlSAX2GetEntity;
    hdlr->getParameterEntity = NULL;
    hdlr->entityDecl = NULL;
    hdlr->attributeDecl = NULL;
    hdlr->elementDecl = NULL;
    hdlr->notationDecl = NULL;
    hdlr->unparsedEntityDecl = NULL;
    hdlr->setDocumentLocator = xmlSAX2SetDocumentLocator;
    hdlr->startDocument = xmlSAX2StartDocument;
    hdlr->endDocument = xmlSAX2EndDocument;
    hdlr->startElement = xmlSAX2StartElement;
    hdlr->endElement = xmlSAX2EndElement;
    hdlr->reference = NULL;
    hdlr->characters = xmlSAX2Characters;
    hdlr->cdataBlock = xmlSAX2CDataBlock;
    hdlr->ignorableWhitespace = xmlSAX2IgnorableWhitespace;
    hdlr->processingInstruction = xmlSAX2ProcessingInstruction;
    hdlr->comment = xmlSAX2Comment;
    hdlr->warning = xmlParserWarning;
    hdlr->error = xmlParserError;
    hdlr->fatalError = xmlParserError;

    hdlr->initialized = 1;
}

#endif /* LIBXML_HTML_ENABLED */

#ifdef LIBXML_DOCB_ENABLED
/**
 * initdocbDefaultSAXHandler:
 * @hdlr:  the SAX handler
 *
 * Initialize the default DocBook SAX version 1 handler
 * DEPRECATED: use xmlSAX2InitDocbDefaultSAXHandler() for the new SAX2 blocks
 */
void
initdocbDefaultSAXHandler(xmlSAXHandlerV1* hdlr)
{
    if (hdlr->initialized == 1)
        return;

    hdlr->internalSubset = xmlSAX2InternalSubset;
    hdlr->externalSubset = NULL;
    hdlr->isStandalone = xmlSAX2IsStandalone;
    hdlr->hasInternalSubset = xmlSAX2HasInternalSubset;
    hdlr->hasExternalSubset = xmlSAX2HasExternalSubset;
    hdlr->resolveEntity = xmlSAX2ResolveEntity;
    hdlr->getEntity = xmlSAX2GetEntity;
    hdlr->getParameterEntity = NULL;
    hdlr->entityDecl = xmlSAX2EntityDecl;
    hdlr->attributeDecl = NULL;
    hdlr->elementDecl = NULL;
    hdlr->notationDecl = NULL;
    hdlr->unparsedEntityDecl = NULL;
    hdlr->setDocumentLocator = xmlSAX2SetDocumentLocator;
    hdlr->startDocument = xmlSAX2StartDocument;
    hdlr->endDocument = xmlSAX2EndDocument;
    hdlr->startElement = xmlSAX2StartElement;
    hdlr->endElement = xmlSAX2EndElement;
    hdlr->reference = xmlSAX2Reference;
    hdlr->characters = xmlSAX2Characters;
    hdlr->cdataBlock = NULL;
    hdlr->ignorableWhitespace = xmlSAX2IgnorableWhitespace;
    hdlr->processingInstruction = NULL;
    hdlr->comment = xmlSAX2Comment;
    hdlr->warning = xmlParserWarning;
    hdlr->error = xmlParserError;
    hdlr->fatalError = xmlParserError;

    hdlr->initialized = 1;
}

#endif /* LIBXML_DOCB_ENABLED */

#endif /* LIBXML_SAX1_ENABLED */

#define bottom_SAX
#include "elfgcchack.h"
#endif /* LIBXML_LEGACY_ENABLED */


text:
"""
Expected Series:
0    10
dtype: int64
"""
import numpy as np
import pandas as pd
from numba import njit

@njit
def series_getitem_scalar():
    series = pd.Series(np.arange(10, 0, -1))  # Series of 10, 9, ..., 1

    return series[0]  # Accessing series by scalar index

print(series_getitem_scalar())


text:
package com.hsuforum.eas;

import java.io.Serializable;

public class DefaultSetting implements Serializable{

    private static final long serialVersionUID = 8322268167179906456L;

    private int dataTableRows;
    private String mailFrom;
	private Boolean devMode=true;
	private Integer rowsOfPerPage;
	private String timeZone;

	public int getDataTableRows() {
		return dataTableRows;
	}
	public void setDataTableRows(int dataTableRows) {
		this.dataTableRows = dataTableRows;
	}
	public String getMailFrom() {
		return mailFrom;
	}
	public void setMailFrom(String mailFrom) {
		this.mailFrom = mailFrom;
	}
	public Boolean getDevMode() {
		return devMode;
	}
	public void setDevMode(Boolean devMode) {
		this.devMode = devMode;
	}
	public Integer getRowsOfPerPage() {
		return rowsOfPerPage;
	}
	public void setRowsOfPerPage(Integer rowsOfPerPage) {
		this.rowsOfPerPage = rowsOfPerPage;
	}
	public String getTimeZone() {
		return timeZone;
	}
	public void setTimeZone(String timeZone) {
		this.timeZone = timeZone;
	}

}


text:
from exsh import clicmd
from difflib import Differ
from time import time
import argparse

class ArgParser(argparse.ArgumentParser):
   def error(self, message):
      sys.stderr.write('error: %s\n' % message)
      self.print_help()
      sys.exit(2)

def main():

    parser = ArgParser(prog='conf_diff.py',
                       description='Compare the saved configuration with the currently running one.')

    parser.add_argument('-d', '--debug',
                         help='Enables verbose logging and leaves temp files for debugging',
                         action='store_true')
    parser.add_argument('-c', '--clean',
                        help='Remove previous debug files. Executes "rm temp_*; rm *.temp"',
                        action='store_true')

    args = parser.parse_args()

    debug = args.debug
    clean = args.clean

    if clean:
        print "DEBUG: Cleaning up previous debug files"
        clicmd("rm temp_*")
        clicmd("rm *.temp")

    print "Comparing configurations, please wait..."

    #create unique names for temp files

    t_stamp = str(time())

    if debug:
        print "DEBUG: Creating temp files"

    saved_name = '/usr/local/cfg/saved_{0}.temp'.format(t_stamp[:-3])
    running_name = '/usr/local/cfg/running_{0}.temp'.format(t_stamp[:-3])
    temp_config = 'temp_{0}'.format(t_stamp[:-3])

    saved_file = open(saved_name, 'w')
    running_file = open(running_name, 'w')

    # find the selected config file

    if debug:
        print "DEBUG: Finding selected config"

    output = clicmd('show switch | include "Config Selected"', True).split()
    selected_config = output[2]
    selected_config = selected_config[:-4]

    # save the running config to a temp file,
    # then convert both config files from XML to human-readable format

    if debug:
        print "DEBUG: Generating temp version of running config"

    clicmd("save config {0}".format(temp_config))

    if debug:
        print "DEBUG: Generating temp cfgmgr version of selected config"

    saved_file.write(clicmd("debug cfgmgr show configuration file {0}".format(selected_config), True))

    if debug:
        print "DEBUG: Generating temp cfgmgr version of running config"

    running_file.write(clicmd("debug cfgmgr show configuration file {0}".format(temp_config), True))

    # set the selected config back, since the save config changed it
    clicmd("use config {0}".format(selected_config), False)

    # close the files, and reopen them for reading
    saved_file.close()
    running_file.close()

    saved_file = open(saved_name, 'r')
    running_file = open(running_name, 'r')

    # diff the two configs

    if debug:
        print "DEBUG: Diffing configs"

    d = Differ()

    diff = list(d.compare(saved_file.readlines(), running_file.readlines()))

    # print the results of the diff
    print " "
    print "If line starts with \'+\', the command has been added since last save."
    print "If line starts with \'-\', the command was present in the last save, and has been deleted."
    print " "
    print "Config changes:"

    for line in diff:
        if line.startswith('+ ') or line.startswith('- '):
            print line[:-1]

    print "Note that this script has cleared the CLI dirty bit. The configuration has not been saved."

    # clean up
    saved_file.close()
    running_file.close()

    # remove files that were opened
    if not debug:
        clicmd("rm {0}".format(saved_name))
        clicmd("rm {0}".format(running_name))
        clicmd("rm {0}.cfg".format(temp_config))

if __name__ == '__main__':
    try:
        main()
    except SystemExit:
        # catch SystemExit to prevent EXOS shell from exiting to login prompt
        pass


text:
package apfe.maze.runtime;

/**
 * The rat wanders through the maze carrying Scanner state and current Path.
 *
 * @author gburdell
 */
public class Rat {

    public Rat(Scanner scanner) {
        m_state = new State(scanner, 0);
        m_path = new Path();
    }

    /**
     * Peek at next available token.
     *
     * @return token next available token.
     */
    public Token peek() {
        return getState().peek();
    }

    public int peekCode() {
        return peek().getCode();
    }

    public State getState() {
        return m_state;
    }

    public Token advance() {
        return getState().advance();
    }

    @Override
    public Rat clone() {
        return new Rat(this);
    }

    public Rat(Rat r) {
        m_state = r.m_state.clone();
        m_path = r.m_path.clone();
    }

    public void destroy() {
        m_state = null;
        m_path.clear();
        m_path = null;
    }

    public Rat addAccepted(Path.Ele acc) {
        m_path.add(acc);
        return this;
    }

    @Override
    public String toString() {
        return m_state.toString() + ": " + m_path.toString();
    }

    private State m_state;
    private Path m_path;
}


text:
package es.lnsd.citikey.di.modules;

import dagger.Module;
import dagger.Provides;
import es.lnsd.citikey.core.datasource.realm.datasources.BeaconRealmDataSource;
import es.lnsd.citikey.core.datasource.realm.datasources.PathRealmDataSource;
import es.lnsd.citikey.core.datasource.realm.datasources.RoomRealmDataSource;
import es.lnsd.citikey.core.repository.beacon.BeaconDatabaseOnlyPolicy;
import es.lnsd.citikey.core.repository.beacon.BeaconPolicyRepository;
import es.lnsd.citikey.core.repository.path.PathDatabaseOnlyPolicy;
import es.lnsd.citikey.core.repository.path.PathPolicyRepository;
import es.lnsd.citikey.core.repository.room.RoomDatabaseOnlyPolicy;
import es.lnsd.citikey.core.repository.room.RoomPolicyRepository;

@Module(includes = RealmModule.class)
public class DataModule {

    //region Beacon
    @Provides
    BeaconDatabaseOnlyPolicy providesBeaconDatabaseOnlyPolicy(BeaconRealmDataSource dataSource) {
        return new BeaconDatabaseOnlyPolicy(dataSource);
    }

    @Provides
    BeaconPolicyRepository providesBeaconPolicyRepository(BeaconDatabaseOnlyPolicy policy) {
        return new BeaconPolicyRepository(policy);
    }
    //endregion

    //region Room
    @Provides
    RoomDatabaseOnlyPolicy providesRoomDatabaseOnlyPolicy(RoomRealmDataSource dataSource) {
        return new RoomDatabaseOnlyPolicy(dataSource);
    }

    @Provides
    RoomPolicyRepository providesRoomPolicyRepository(RoomDatabaseOnlyPolicy policy) {
        return new RoomPolicyRepository(policy);
    }
    //endregion

    //region Path
    @Provides
    PathDatabaseOnlyPolicy providesPathDatabaseOnlyPolicy(PathRealmDataSource dataSource) {
        return new PathDatabaseOnlyPolicy(dataSource);
    }

    @Provides
    PathPolicyRepository providesPathPolicyRepository(PathDatabaseOnlyPolicy policy) {
        return new PathPolicyRepository(policy);
    }
    //endregion
}


text:
import {Injectable} from '@angular/core';
import {Observable, Subscriber} from 'rxjs/Rx'

export type PetKind = "chicken" | "cat" | "dog";

export interface IPet {
    name: string,
    kind: PetKind,
    img: string,
    profileText: string
}

@Injectable()
export class PetService {
    static DUMMYPETS: IPet[] = [
        {
            name: "Princess",
            kind: "chicken",
            img: "/assets/chicken1.jpg",
            profileText: "Meet Princess Fluffybutt! She is one of the fluffiest chickens you will ever meet. Most often you'll find Princess cuddled up in the warmest spot she can find, and if that happens to be in your lap, well then that's fine for her too! Princess also enjoys nomming treats out of your hand, clucking softly under her breath, and following her three sisters around the yard. Get to know Princess today!"
        }, {
            name: "MrFuzz",
            kind: "cat",
            img: "/assets/cat1.jpg",
            profileText: "MrFuzz loves belly rubs, and likes playing with pieces of string"
        }, {
            name: "Burt",
            kind: "dog",
            img: "/assets/dog1.jpg",
            profileText: "Burt looks cute, but is in reality a though guy. Secretly wants to work for the FBI"
        }, {
            name: "MissPoes",
            kind: "cat",
            img: "/assets/cat2.jpg",
            profileText: "MissPoes is a classy lady who appreciates gentle pets"
        }, {
            name: "Lady",
            kind: "dog",
            img: "/assets/dog2.jpg",
            profileText: "Lady isn't always very lady-like. She loves rolling in the mud and barking at naughty squirrels"
        }, {
            name: "Grumpy",
            kind: "cat",
            img: "/assets/cat3.jpg",
            profileText: "Grumpy basically hates everything, especially dogs. He does looove lasagne though"
        }, {
            name: "Bobby",
            kind: "dog",
            img: "/assets/dog3.jpg",
            profileText: "Bobby loves to fetch balls and chase rabbits. Great with kids."
        }
    ];

    getPets(): Observable<IPet[]> {
        return new Observable<IPet[]>((s: Subscriber<IPet[]>) => {
            s.next(PetService.DUMMYPETS);
            s.complete();
        });
    }
}


text:
========================
Authors and contributors
========================

The following people have contributed code and/or ideas to the current version
of Neo. The institutional affiliations are those at the time of the contribution,
and may not be the current affiliation of a contributor.

* Samuel Garcia [1]
* Andrew Davison [2]
* Chris Rodgers [3]
* Pierre Yger [2]
* Yann Mahnoun [4]
* Luc Estabanez [2]
* Andrey Sobolev [5]
* Thierry Brizzi [2]
* Florent Jaillet [6]
* Philipp Rautenberg [5]
* Thomas Wachtler [5]
* Cyril Dejean [7]
* Robert Pröpper [8]
* Domenico Guarino [2]
* Achilleas Koutsou [5]
* Erik Li [9]
* Georg Raiser [10]
* Joffrey Gonin [2]
* Kyler Brown [?]
* Mikkel Elle Lepperød [11]
* C Daniel Meliza [12]
* Julia Sprenger [13]
* Maximilian Schmidt [13]
* Johanna Senk [13]
* Carlos Canova [13]
* Hélissande Fragnaud [2]
* Mark Hollenbeck [14]
* Mieszko Grodzicki

1. Centre de Recherche en Neuroscience de Lyon, CNRS UMR5292 - INSERM U1028 - Universite Claude Bernard Lyon 1
2. Unité de Neuroscience, Information et Complexité, CNRS UPR 3293, Gif-sur-Yvette, France
3. University of California, Berkeley
4. Laboratoire de Neurosciences Intégratives et Adaptatives, CNRS UMR 6149 - Université de Provence, Marseille, France
5. G-Node, Ludwig-Maximilians-Universität, Munich, Germany
6. Institut de Neurosciences de la Timone, CNRS UMR 7289 - Université d'Aix-Marseille, Marseille, France
7. Centre de Neurosciences Integratives et Cignitives, UMR 5228 - CNRS - Université Bordeaux I - Université Bordeaux II
8. Neural Information Processing Group, TU Berlin, Germany
9. Department of Neurobiology & Anatomy, Drexel University College of Medicine, Philadelphia, PA, USA
10. University of Konstanz, Konstanz, Germany
11. Centre for Integrative Neuroplasticity (CINPLA), University of Oslo, Norway
12. University of Virginia
13. INM-6, Forschungszentrum Jülich, Germany
14. University of Texas at Austin

If we've somehow missed you off the list we're very sorry - please let us know.


text:
using System.Collections.Immutable;
using System.Numerics;

namespace xFunc.Maths.Expressions;

/// <summary>
/// Represents the Logarithm function.
/// </summary>
public class Log : BinaryExpression
{
    /// <summary>
    /// Initializes a new instance of the <see cref="Log"/> class.
    /// </summary>
    /// <param name="base">The right operand.</param>
    /// <param name="arg">The left operand.</param>
    /// <seealso cref="IExpression"/>
    public Log(IExpression @base, IExpression arg)
        : base(@base, arg)
    {
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="Log"/> class.
    /// </summary>
    /// <param name="arguments">The list of arguments.</param>
    /// <seealso cref="IExpression"/>
    public Log(ImmutableArray<IExpression> arguments)
        : base(arguments)
    {
    }

    /// <inheritdoc />
    public override object Execute(ExpressionParameters? parameters)
    {
        var leftResult = Left.Execute(parameters);
        var rightResult = Right.Execute(parameters);

        return (leftResult, rightResult) switch
        {
            (NumberValue left, NumberValue right) => NumberValue.Log(right, left),
            (NumberValue left, Complex complex) => NumberValue.Log(complex, left),
            _ => throw new ResultIsNotSupportedException(this, leftResult, rightResult),
        };
    }

    /// <inheritdoc />
    protected override TResult AnalyzeInternal<TResult>(IAnalyzer<TResult> analyzer)
        => analyzer.Analyze(this);

    /// <inheritdoc />
    protected override TResult AnalyzeInternal<TResult, TContext>(
        IAnalyzer<TResult, TContext> analyzer,
        TContext context)
        => analyzer.Analyze(this, context);

    /// <inheritdoc />
    public override IExpression Clone(IExpression? left = null, IExpression? right = null)
        => new Log(left ?? Left, right ?? Right);
}


text:
#region

using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using Cirrious.CrossCore;
using Dots.Core.Models;
using Dots.Core.Services.Security;

#endregion

namespace Dots.Core.ViewModels
{
    public class BaseViewModel<VM, M> : BaseViewModel
        where VM : IBaseViewModel
        where M : IBaseModel, new()
    {
        private M model;
        private bool showModal;

        public BaseViewModel()
        {
        }

        #region Properties

        public override Guid Id
        {
            get { return Model.Id; }
            set
            {
                if (Model.Id == value) return;
                Model.Id = value;
                RaisePropertyChanged(() => Id);
            }
        }

        public override int Index
        {
            get { return Model.Index; }
            set
            {
                if (Model.Index == value) return;
                Model.Index = value;
                RaisePropertyChanged(() => Index);
            }
        }

        public virtual M Model
        {
            get { return EqualityComparer<M>.Default.Equals(model, default(M)) ? new M() : model; }
            set { model = value; }
        }

        [XmlIgnore]
        public bool IsAdmin
        {
            get { return Mvx.Resolve<ISecurityService>().IsAdministrator; }
        }

        public bool ShowModal
        {
            get { return showModal; }
            set
            {
                showModal = value;
                RaisePropertyChanged(() => ShowModal);
            }
        }

        #endregion
    }
}


text:
from __future__ import unicode_literals

from django.apps import AppConfig

class ApiCallConfig(AppConfig):
    name = 'api_call'


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

<title>PrioList (MaltParser 1.8.1)</title>
<meta name="date" content="2014-11-22">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

MaltParser 1.8.1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.maltparser.core.syntaxgraph.headrules

Class PrioList

java.lang.Object

java.util.AbstractCollection<E>

java.util.AbstractList<E>

java.util.ArrayList<PrioSet>

org.maltparser.core.syntaxgraph.headrules.PrioList

All Implemented Interfaces:

java.io.Serializable, java.lang.Cloneable, java.lang.Iterable<PrioSet>, java.util.Collection<PrioSet>, java.util.List<PrioSet>, java.util.RandomAccess

public class PrioList
extends java.util.ArrayList<PrioSet>

Author:

Johan Hall

See Also:

Serialized Form

Field Summary

Fields

Modifier and Type
Field and Description

protected Direction
direction

protected HeadRule
headRule

static long
serialVersionUID

Fields inherited from class java.util.AbstractList

modCount

Constructor Summary

Constructors

Constructor and Description

PrioList(HeadRule headRule,
                java.lang.String listSpec)

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(java.lang.Object obj)

DataFormatInstance
getDataFormatInstance()

PhraseStructureNode
getHeadChild(NonTerminalNode nt)

HeadRule
getHeadRule()

org.apache.log4j.Logger
getLogger()

SymbolTableHandler
getSymbolTableHandler()

int
hashCode()

void
init(java.lang.String listSpec)

void
setHeadRule(HeadRule headRule)

java.lang.String
toString()

Methods inherited from class java.util.ArrayList

add, add, addAll, addAll, clear, clone, contains, ensureCapacity, get, indexOf, isEmpty, iterator, lastIndexOf, listIterator, listIterator, remove, remove, removeAll, removeRange, retainAll, set, size, subList, toArray, toArray, trimToSize

Methods inherited from class java.util.AbstractCollection

containsAll

Methods inherited from class java.lang.Object

finalize, getClass, notify, notifyAll, wait, wait, wait

Methods inherited from interface java.util.List

containsAll

Field Detail

serialVersionUID

public static final long serialVersionUID

See Also:

Constant Field Values

headRule

protected HeadRule headRule

direction

protected Direction direction

Constructor Detail

PrioList

public PrioList(HeadRule headRule,
        java.lang.String listSpec)
         throws MaltChainedException

Throws:

MaltChainedException

Method Detail

init

public void init(java.lang.String listSpec)
          throws MaltChainedException

Throws:

MaltChainedException

getHeadChild

public PhraseStructureNode getHeadChild(NonTerminalNode nt)
                                 throws MaltChainedException

Throws:

MaltChainedException

getLogger

public org.apache.log4j.Logger getLogger()

getDataFormatInstance

public DataFormatInstance getDataFormatInstance()

getSymbolTableHandler

public SymbolTableHandler getSymbolTableHandler()

getHeadRule

public HeadRule getHeadRule()

setHeadRule

public void setHeadRule(HeadRule headRule)

equals

public boolean equals(java.lang.Object obj)

Specified by:

equals in interface java.util.Collection<PrioSet>

Specified by:

equals in interface java.util.List<PrioSet>

Overrides:

equals in class java.util.AbstractList<PrioSet>

hashCode

public int hashCode()

Specified by:

hashCode in interface java.util.Collection<PrioSet>

Specified by:

hashCode in interface java.util.List<PrioSet>

Overrides:

hashCode in class java.util.AbstractList<PrioSet>

toString

public java.lang.String toString()

Overrides:

toString in class java.util.AbstractCollection<PrioSet>

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

MaltParser 1.8.1

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright 2007-2014 Johan Hall, Jens Nilsson and Joakim Nivre.


text:
/**
 * Helps with output
 */
export declare class OutputHelper {
    /**
     * Formats the error with markup
     * @param message Message to format
     * @returns Formatted string
     */
    static formatError(message: string): string;
    /**
     * Formats the information message
     * @param message Message to format
     * @returns Formatted string
     */
    static formatInfo(message: string): string;
    /**
     * Formats the information
     * @param message Message to format
     * @returns Formatted string
     */
    static formatDescription(message: string): string;
    /**
     * Formats the hint message
     * @param message Message to format
     * @returns Formatted string
     */
    static formatHint(message: string): string;
    /**
     * Logs information to the console
     * @param message Message to write
     */
    static error(message: string): void;
    /**
     * Logs information to the console
     * @param message Message to write
     */
    static info(message: string): void;
}
//# sourceMappingURL=helper.d.ts.map


text: import './components/App';


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

<TITLE>
Uses of Class com.sun.cldc.jna.Structure (2013 FRC Java API)
</TITLE>

<META NAME="date" CONTENT="2014-01-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Class
com.sun.cldc.jna.Structure

Packages that use Structure

com.sun.cldc.jna
The CLDC/JNA package contains classes that help import native data structures and functions from Java code without writing
C code.

com.sun.squawk.platform.posix.natives

edu.wpi.first.wpilibj.communication
Provides classes for communicating with the driver station and synchronizing with C/C++ code.

edu.wpi.first.wpilibj.image
Provides classes to access National Instrument's nivison library for machine vision enables automated image processing
for color identification, tracking and analysis.

Uses of Structure in com.sun.cldc.jna

Subclasses of Structure in com.sun.cldc.jna

 class
DynamicStructure

          A DynamicStructure is a structure with support for getting the field offsets
 for a particular platform from native code.

 class
OpaqueStructure

          This is a "Structure" that we'll never look at the fields of.

Fields in com.sun.cldc.jna declared as Structure

static Structure
Structure.NULL

          Singleton object that can be used as a NULL structure instance.

Methods in com.sun.cldc.jna that return Structure

static Structure
Function.returnStruct(Class klass,
             int ptr)

          Standard conversion function that creates an structure instance of type klass from a C address ptr.

Uses of Structure in com.sun.squawk.platform.posix.natives

Subclasses of Structure in com.sun.squawk.platform.posix.natives

static class
LibC.stat

          C struct stat
 //    struct stat {
 //        dev_t                st_dev;         /* [XSI] ID of device containing file             4 0
 //        ino_t                st_ino;         /* [XSI] File serial number                       4 4
 //        mode_t               st_mode;        /* [XSI] Mode of file (see below)             2 8
 //        nlink_t              st_nlink;       /* [XSI] Number of hard links                 2 10
 //        uid_t                st_uid;         /* [XSI] User ID of the file                      4 12
 //        gid_t                st_gid;         /* [XSI] Group ID of the file                     4 16
 //        dev_t                st_rdev;        /* [XSI] Device ID                                4 20
 //        time_t               st_atime;       /* [XSI] Time of last access                  4 24
 //        long         st_atimensec;   /* nsec of last access                        4 28
 //        time_t               st_mtime;       /* [XSI] Last data modification time          4 32
 //        long         st_mtimensec;   /* last data modification nsec                4 36
 //        time_t               st_ctime;       /* [XSI] Time of last status change           4 40
 //        long         st_ctimensec;   /* nsec of last status change                 4 44
 //        off_t                st_size;        /* [XSI] file size, in bytes                      8 48
 //        blkcnt_t     st_blocks;      /* [XSI] blocks allocated for file                8
 //        blksize_t    st_blksize;     /* [XSI] optimal blocksize for I/O                4
 //        __uint32_t   st_flags;       /* user defined flags for file                4
 //        __uint32_t   st_gen;         /* file generation number                     4
 //        __int32_t    st_lspare;      /* RESERVED: DO NOT USE!                          4
 //        __int64_t    st_qspare[2];   /* RESERVED: DO NOT USE!                      16
 //     };

static class
LibCImpl.statImpl

static class
NetDB.hostent

          C STRUCTURE HostEnt
            struct  hostent {
                     char    *h_name;         official name of host
                     char    **h_aliases;     alias list
                     int     h_addrtype;      host address type
                     int     h_length;        length of address
                     char    **h_addr_list;   list of addresses from name server
             };
             #define h_addr  h_addr_list[0]  address, for backward compatibility

static class
NetDBImpl.hostentImpl

static class
Socket.sockaddr_in

          C STRUCTURE sockaddr_in  /
     struct sockaddr_in {
        u_char  sin_len;     1
        u_char  sin_family;  1
        u_short sin_port;    2
        struct  in_addr sin_addr; 4
        char    sin_zero[8];     8
     };

     struct sockaddr {
        __uint8_t       sa_len;         /* total length
        sa_family_t     sa_family;      /* [XSI] address family
        char            sa_data[14];    /* [XSI] addr value (actually larger)
};

static class
SocketImpl.sockaddr_inImpl

static class
Time.timeval

          struct timeval {
             time_t       tv_sec;   // seconds since Jan.

static class
TimeImpl.timevalImpl

Uses of Structure in edu.wpi.first.wpilibj.communication

Subclasses of Structure in edu.wpi.first.wpilibj.communication

 class
FRCCommonControlData

          Structure for data exchanged between the robot and the driver station.

static class
FRCControl.DynamicControlData

Uses of Structure in edu.wpi.first.wpilibj.image

Subclasses of Structure in edu.wpi.first.wpilibj.image

 class
CurveOptions

 class
EllipseDescriptor

static class
NIVision.Range

static class
NIVision.Rect

 class
RegionOfInterest

          This is a dummy class which needs to be filled in.

 class
ShapeDetectionOptions

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

"
2013 FRC Java API
"

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

"For updated information see the Java FRC site"


text:
package org.javamoney.moneta.format;

import static org.testng.Assert.assertEquals;
import org.javamoney.moneta.Money;
import org.javamoney.moneta.function.MoneyProducer;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javax.money.CurrencyUnit;
import javax.money.Monetary;
import javax.money.MonetaryAmount;
import javax.money.format.AmountFormatContext;
import javax.money.format.MonetaryAmountFormat;
import javax.money.format.MonetaryParseException;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.Locale;

public class MonetaryAmountDecimalFormatTest {

    private static final int EXAMPLE_VALUE = 10;

    private  MonetaryAmountFormat format;

    private Locale locale;

    private CurrencyUnit currencyUnit;

    private NumberFormat numberFormat;

    @BeforeMethod
    public void setup() {
        locale = Locale.US;
        currencyUnit = Monetary.getCurrency(locale);
        currencyUnit = Monetary.getCurrency(locale);
        format = MonetaryAmountDecimalFormatBuilder.of(locale).withProducer(new MoneyProducer())
                .withCurrencyUnit(currencyUnit).build();
        numberFormat = NumberFormat.getCurrencyInstance(locale);
    }

    @Test
    public void shouldReturnContext() {
        AmountFormatContext context = format.getContext();
        Assert.assertEquals(MonetaryAmountDecimalFormat.STYLE, context.getFormatName());
    }

    @Test(expectedExceptions = NullPointerException.class)
    public void shouldReturnsErrorWhenAppendableIsNull() throws IOException {
        format.print(null, null);
    }

    @Test
    public void shouldPrintNullWhenMonetaryAmountIsNull() throws IOException {
        StringBuilder sb = new StringBuilder();
        format.print(sb, null);
        assertEquals(sb.toString(), "null");
    }

    @Test
    public void shouldPrintMonetaryAmount() throws IOException {
        StringBuilder sb = new StringBuilder();
        MonetaryAmount money = Money.of(EXAMPLE_VALUE, currencyUnit);
        format.print(sb, money);

        assertEquals(sb.toString(), numberFormat.format(EXAMPLE_VALUE));
    }

    @Test
    public void shouldQueryFromNullWhenMonetaryAmountIsNull() throws IOException {
        assertEquals(format.queryFrom(null), "null");
    }

    @Test
    public void shouldQueryFromMonetaryAmount() throws IOException {
        MonetaryAmount money = Money.of(EXAMPLE_VALUE, currencyUnit);
        assertEquals(format.queryFrom(money), numberFormat.format(EXAMPLE_VALUE));
    }

    @Test(expectedExceptions = NullPointerException.class)
    public void shouldReturnErrorParseWhenMonetaryAmountIsNull() {
        format.parse(null);
    }

    @Test(expectedExceptions = MonetaryParseException.class)
    public void shouldReturnErrorParseWhenMonetaryAmountIsInvalid() {
        format.parse("ERROR");
    }

    @Test
    public void shouldParseMonetaryAmount() throws IOException {
        MonetaryAmount money = Money.of(EXAMPLE_VALUE, currencyUnit);
        String parse = format.queryFrom(money);
        assertEquals(format.parse(parse), money);
    }

}


text:
package exercises.exercise3;

import java.io.IOException;

public class Application {

    public static void main(String[] args) {
        TrafficLight t = new TrafficLight();
        while (true){
            t.tick(1.0f);
            System.out.println(t);

            try {
                System.in.read();
            }catch(IOException ioe){
                System.err.println(ioe);
            }
        }
    }
}


text:
FactoryGirl.define do
  factory :snippet, class: OpenConferenceWare::Snippet do
    sequence(:slug){|n| "test-snippet-#{n}"}
    description "A testing snippet"
    content "This is only a test."
  end
end


text:
<?php

namespace Nette\Security;

use Nette;

/**
 * Represents resource, an object to which access is controlled.
 *
 * @author     David Grudl
 */
interface IResource
{

	/**
	 * Returns a string identifier of the Resource.
	 * @return string
	 */
	public function getResourceId();

}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from ray.rllib.agents.dqn.apex import ApexTrainer
from ray.rllib.agents.dqn.dqn import DQNTrainer, DEFAULT_CONFIG
from ray.rllib.utils import renamed_agent

DQNAgent = renamed_agent(DQNTrainer)
ApexAgent = renamed_agent(ApexTrainer)

__all__ = [
    "DQNAgent", "ApexAgent", "ApexTrainer", "DQNTrainer", "DEFAULT_CONFIG"
]


text:
from math import log, ceil

from numpy import zeros, fill_diagonal, random, sign

from neupy.utils import format_data
from neupy.network.utils import step
from neupy.core.properties import Property
from .utils import bin2sign, hopfield_energy
from .base import DiscreteMemory

__all__ = ('DiscreteHopfieldNetwork',)

class DiscreteHopfieldNetwork(DiscreteMemory):
    """ Discrete Hopfield Network. Memory algorithm which works only with
    binary vectors.

    Parameters
    ----------
    {DiscreteMemory.mode}
    {DiscreteMemory.n_times}
    check_limit : bool
        Option enable a limit of patterns control for the network using
        logarithmically proportion rule. Defaults to ``True``.

    Methods
    -------
    energy(input_data)
        Compute Discrete Hopfiel Energy.
    train(input_data)
        Save input data pattern into the network memory.
    predict(input_data, n_times=None)
        Recover data from the memory using input pattern.
        For the prediction procedure you can control number of iterations.
        If you set up this value equal to ``None`` then the value would be
        equal to the value that you set up for the property with
        the same name - ``n_times``.

    Notes
    -----
    * Input and output vectors should contain only binary values.

    Examples
    --------
    >>> import numpy as np
    >>> from neupy import algorithms
    >>>
    >>> def draw_bin_image(image_matrix):
    ...     for row in image_matrix.tolist():
    ...         print('| ' + ' '.join(' *'[val] for val in row))
    ...
    >>> zero = np.matrix([
    ...     0, 1, 1, 1, 0,
    ...     1, 0, 0, 0, 1,
    ...     1, 0, 0, 0, 1,
    ...     1, 0, 0, 0, 1,
    ...     1, 0, 0, 0, 1,
    ...     0, 1, 1, 1, 0
    ... ])
    >>>
    >>> one = np.matrix([
    ...     0, 1, 1, 0, 0,
    ...     0, 0, 1, 0, 0,
    ...     0, 0, 1, 0, 0,
    ...     0, 0, 1, 0, 0,
    ...     0, 0, 1, 0, 0,
    ...     0, 0, 1, 0, 0
    ... ])
    >>>
    >>> two = np.matrix([
    ...     1, 1, 1, 0, 0,
    ...     0, 0, 0, 1, 0,
    ...     0, 0, 0, 1, 0,
    ...     0, 1, 1, 0, 0,
    ...     1, 0, 0, 0, 0,
    ...     1, 1, 1, 1, 1,
    ... ])
    >>>
    >>> half_zero = np.matrix([
    ...     0, 1, 1, 1, 0,
    ...     1, 0, 0, 0, 1,
    ...     1, 0, 0, 0, 1,
    ...     0, 0, 0, 0, 0,
    ...     0, 0, 0, 0, 0,
    ...     0, 0, 0, 0, 0,
    ... ])
    >>>
    >>> draw_bin_image(zero.reshape((6, 5)))
    |   * * *
    | *       *
    | *       *
    | *       *
    | *       *
    |   * * *
    >>> draw_bin_image(half_zero.reshape((6, 5)))
    |   * * *
    | *       *
    | *       *
    |
    |
    |
    >>> data = np.concatenate([zero, one, two], axis=0)
    >>>
    >>> dhnet = algorithms.DiscreteHopfieldNetwork()
    >>> dhnet.train(data)
    >>>
    >>> result = dhnet.predict(half_zero)
    >>> draw_bin_image(result.reshape((6, 5)))
    |   * * *
    | *       *
    | *       *
    | *       *
    | *       *
    |   * * *

    See Also
    --------
    :ref:`password-recovery`: Password recovery with Discrete Hopfield Network.
    :ref:`discrete-hopfield-network`: Discrete Hopfield Network tutorial.
    """

    check_limit = Property(default=True, expected_type=bool)

    def __init__(self, **options):
        super(DiscreteHopfieldNetwork, self).__init__(**options)
        self.n_remembered_data = 0

    def train(self, input_data):
        self.discrete_validation(input_data)

        input_data = bin2sign(input_data)
        input_data = format_data(input_data, is_feature1d=False)

        nrows, n_features = input_data.shape
        nrows_after_update = self.n_remembered_data + nrows

        if self.check_limit:
            memory_limit = ceil(n_features / (2 * log(n_features)))

            if nrows_after_update > memory_limit:
                raise ValueError("You can't memorize more than {0} "
                                 "samples".format(memory_limit))

        weight_shape = (n_features, n_features)

        if self.weight is None:
            self.weight = zeros(weight_shape, dtype=int)

        if self.weight.shape != weight_shape:
            raise ValueError("Invalid input shapes. Number of input "
                             "features must be equal to {} and {} output "
                             "features".format(*weight_shape))

        self.weight = input_data.T.dot(input_data)
        fill_diagonal(self.weight, zeros(len(self.weight)))
        self.n_remembered_data = nrows_after_update

    def predict(self, input_data, n_times=None):
        self.discrete_validation(input_data)
        input_data = format_data(bin2sign(input_data), is_feature1d=False)

        if self.mode == 'async':
            if n_times is None:
                n_times = self.n_times

            _, n_features = input_data.shape
            output_data = input_data

            for _ in range(n_times):
                position = random.randint(0, n_features - 1)
                raw_new_value = output_data.dot(self.weight[:, position])
                output_data[:, position] = sign(raw_new_value)
        else:
            output_data = input_data.dot(self.weight)

        return step(output_data).astype(int)

    def energy(self, input_data):
        self.discrete_validation(input_data)
        input_data = bin2sign(input_data)
        input_data = format_data(input_data, is_feature1d=False)
        nrows, n_features = input_data.shape

        if nrows == 1:
            return hopfield_energy(self.weight, input_data, input_data)

        output = zeros(nrows)
        for i, row in enumerate(input_data):
            output[i] = hopfield_energy(self.weight, row, row)

        return output


text:
from bs4 import BeautifulSoup
from bs4.element import Comment
import re

class Document(object):

    def __init__(self, doc_id, file = None, line = None):
        if file is not None and line is None:
            name = file.name
            if str(file.name).startswith('Users/tweni/Documents/workspace/SIRS/data/'):
                name = file.name[len('Users/tweni/Documents/workspace/SIRS/data/'):]
            self.name = name
            self.doc_id = doc_id
            self.num_tokens = dict()
            self.resources = dict()
        elif file is None and line is not None:
            self.name = ''
            self.doc_id = doc_id
            self.num_tokens = dict()
            self.resources = dict()
            self.read_from_index(line)
        else:
            raise Exception('Must pass either file or line')

    def get_name(self):
        return self.name

    def get_doc_id(self):
        return self.doc_id

    def get_num_tokens(self, field):
        return self.num_tokens[field]

    def get_resources(self):
        return self.resources

    def write_to_index(self):
        """
        Creates a String to write to direct document index including all extra information. This is expected to be
        overridden by subclasses
        :return: String representation of a document
        """

        sb = list()
        sb.append(str(self.get_doc_id()) + '\t' + self.get_name() + '\t' + self.print_num_tokens())
        for k,v in self.resources.items():
            sb.append(k + '-#-' + v)

        sb.append('\n')
        return '\t'.join(sb)

    def print_num_tokens(self):
        sb = list()
        for k,v in self.num_tokens.items():
            sb.append(str(k) + ':' + str(v))
        return ','.join(sb)

    def read_from_index(self, line):
        """
        Reads data that was previous written to file by writeToIndex() function.
        Should be overridden when writeToIndex is overridden

        :param line: line to read
        :return:
        """
        s = line.split('\t')
        self.doc_id = s[0]
        self.name = s[1]
        num_toks_list = s[2].split(',')
        for toks in num_toks_list:
            r = toks.split(':')
            f = Field(int(r[0]))
            self.num_tokens[f.field] = int(r[1])

        for i in range(3,len(s)):
            r = s[i].split('-#-')
            if len(r) == 2:
                str(r[1]).replace('"', '')
                self.resources[r[0]] = r[1]

class HTMLDocument(Document):
    def __init__(self, doc_id, file, line):
        if file is not None and line is None:
            super().__init__(doc_id, file=file)
        elif file is None and line is not None:
            super().__init__(doc_id, line=line)
        else:
            raise Exception('Must pass either file or line')

    @staticmethod
    def tag_visible(element):
        if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
            return False
        if isinstance(element, Comment):
            return False
        return True

    @staticmethod
    def text_from_html(body):
        texts = body.findAll(text=True)
        visible_texts = filter(HTMLDocument.tag_visible, texts)
        return u" ".join(t.strip() for t in visible_texts)

    def parse(self, doc_id, file):
        print('HTML Parsing invoked')
        f = Fields()
        f.add_field('body')
        f.add_field('link')
        f.add_field('title')

        html = b''.join(file.readlines())
        tokens = list()
        tokenizer = WhitespaceTokenizer()
        normalizer = CaseFoldingNormalizer()

        doc = BeautifulSoup(html, features='lxml')

        # remove all script and style elements
        for script in doc(["script", "style"]):
            script.extract()

        titles = [title.get_text() for title in doc.find_all('title')]
        num_title_tokens = 0
        if len(titles) >= 1:
            title = titles[0]
            self.resources['title'] = title.replace('\n', ' ')
            title_tokens = tokenizer.tokenizer_str(title)
            title_tokens = normalizer.normalize(title_tokens)
            for tok in title_tokens:
                tokens.append(Token(tok, Fields().get_field_id('title')))
                num_title_tokens += 1
        self.num_tokens[Fields().get_field_id('title')] = num_title_tokens
        text = HTMLDocument.text_from_html(doc)

        content = tokenizer.tokenizer_str(text)
        content = normalizer.normalize(content)
        content_toks = 0
        for s in content:
            tokens.append(Token(s, Fields().get_field_id('body')))
            content_toks += 1
        self.num_tokens[Fields().get_field_id('body')] = content_toks

        for link in doc.find_all('a', href=True):
            url = link['href']
            #parse.urljoin(web_url, link['href'])
            anchor_toks = list()
            anchors = tokenizer.tokenizer_str(link.text)
            anchors = normalizer.normalize(anchors)
            for s in anchors:
                anchor_toks.append(Token(s, Fields().get_field_id('link')))
            self.resources['l'+url] = anchor_toks
        #self.num_tokens[Fields.get_field_id('link')] = len(anchor_toks)
        return tokens

class Fields(object):

    class __Fields:

        def __init__(self):
            self.__fields = dict()
            self.__weights = dict()

    instance = None

    def __init__(self):
        if not Fields.instance:
            Fields.instance = Fields.__Fields()
        else:
            pass

    def __getattr__(self, name):
        return getattr(self.instance, name)

    def add_field(self, field):
        if field in Fields.instance.__fields:
            return False
        else:
            new_field = Field(len(self.__fields))
            self.__fields[field] = new_field

    def get_field_id(self, field):
        return self.__fields[field].field

    def get_fields(self):
        return self.__fields.values()

    def get_items(self):
        return self.__fields.items()

    def get_weight(self, field):
        return self.__weights[field]

    @staticmethod
    def load_from_inverted_index(field_string):
        me = Fields()
        fs = field_string.strip().split(';')
        for f in fs:
            fl = f.split(',')
            me.__fields[fl[0]] = Field(int(fl[1]))

        w = float(1)/len(me.__fields)

        for k in me.__fields.values():
            me.__weights[k.field] = w

    def assign_weights(self, weights):
        for k,v in weights.items():
            self.__weights[self.get_field_id(k)] = v

        # normalize
        __sum = 0.0
        for w in self.__weights.values():
            __sum += w
        for k in self.__weights.keys():
            self.__weights[k] = self.__weights[k]/float(__sum)

class Field(object):
    def __init__(self, field):
        self.field = field

    def __eq__(self, other):
        return self.field == other.args

class Token(object):
    def __init__(self, term, field):
        self.term = term
        self.field = field

    def get_token_string(self):
        return self.term

    def get_field(self):
        return self.field

    def __eq__(self, other):
        return self.field == other.args

class WhitespaceTokenizer(object):
    @staticmethod
    def tokenizer_str(string):
        return re.split('[^a-zA-Z]', string)

class CaseFoldingNormalizer(object):
    @staticmethod
    def normalize(token_list):
        new_list = list()
        for tok in token_list:
            tok = tok.strip()
            if len(tok) == 0 :
                continue
            new_list.append(str(tok).lower())
        return new_list


text:
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#include <algorithm>

#include "xfa/src/fgas/src/fgas_base.h"
#include "fx_memory.h"
#define FX_4BYTEALIGN(size) (((size) + 3) / 4 * 4)
IFX_MEMAllocator* FX_CreateAllocator(FX_ALLOCTYPE eType,
                                     size_t chunkSize,
                                     size_t blockSize) {
  switch (eType) {
#ifndef _FXEMB
    case FX_ALLOCTYPE_Dynamic:
      return new CFX_DynamicStore(chunkSize);
#endif
    case FX_ALLOCTYPE_Default:
      return new CFX_DefStore();
    case FX_ALLOCTYPE_Static:
      return new CFX_StaticStore(chunkSize);
    case FX_ALLOCTYPE_Fixed:
      return new CFX_FixedStore(blockSize, chunkSize);
    default:
      return NULL;
  }
}
CFX_StaticStore::CFX_StaticStore(size_t iDefChunkSize)
    : m_iAllocatedSize(0),
      m_iDefChunkSize(iDefChunkSize),
      m_pChunk(NULL),
      m_pLastChunk(NULL) {
  FXSYS_assert(m_iDefChunkSize != 0);
}
CFX_StaticStore::~CFX_StaticStore() {
  FX_LPSTATICSTORECHUNK pChunk, pNext;
  pChunk = m_pChunk;
  while (pChunk != NULL) {
    pNext = pChunk->pNextChunk;
    FX_Free(pChunk);
    pChunk = pNext;
  }
}
FX_LPSTATICSTORECHUNK CFX_StaticStore::AllocChunk(size_t size) {
  FXSYS_assert(size != 0);
  FX_LPSTATICSTORECHUNK pChunk = (FX_LPSTATICSTORECHUNK)FX_Alloc(
      uint8_t, sizeof(FX_STATICSTORECHUNK) + size);
  pChunk->iChunkSize = size;
  pChunk->iFreeSize = size;
  pChunk->pNextChunk = NULL;
  if (m_pLastChunk == NULL) {
    m_pChunk = pChunk;
  } else {
    m_pLastChunk->pNextChunk = pChunk;
  }
  m_pLastChunk = pChunk;
  return pChunk;
}
FX_LPSTATICSTORECHUNK CFX_StaticStore::FindChunk(size_t size) {
  FXSYS_assert(size != 0);
  if (m_pLastChunk == NULL || m_pLastChunk->iFreeSize < size) {
    return AllocChunk(std::max(m_iDefChunkSize, size));
  }
  return m_pLastChunk;
}
void* CFX_StaticStore::Alloc(size_t size) {
  size = FX_4BYTEALIGN(size);
  FXSYS_assert(size != 0);
  FX_LPSTATICSTORECHUNK pChunk = FindChunk(size);
  FXSYS_assert(pChunk != NULL && pChunk->iFreeSize >= size);
  uint8_t* p = (uint8_t*)pChunk;
  p += sizeof(FX_STATICSTORECHUNK) + pChunk->iChunkSize - pChunk->iFreeSize;
  pChunk->iFreeSize -= size;
  m_iAllocatedSize += size;
  return p;
}
size_t CFX_StaticStore::SetDefChunkSize(size_t size) {
  FXSYS_assert(size != 0);
  size_t v = m_iDefChunkSize;
  m_iDefChunkSize = size;
  return v;
}
CFX_FixedStore::CFX_FixedStore(size_t iBlockSize, size_t iBlockNumsInChunk)
    : m_iBlockSize(FX_4BYTEALIGN(iBlockSize)),
      m_iDefChunkSize(FX_4BYTEALIGN(iBlockNumsInChunk)),
      m_pChunk(NULL) {
  FXSYS_assert(m_iBlockSize != 0 && m_iDefChunkSize != 0);
}
CFX_FixedStore::~CFX_FixedStore() {
  FX_LPFIXEDSTORECHUNK pChunk, pNext;
  pChunk = m_pChunk;
  while (pChunk != NULL) {
    pNext = pChunk->pNextChunk;
    FX_Free(pChunk);
    pChunk = pNext;
  }
}
FX_LPFIXEDSTORECHUNK CFX_FixedStore::AllocChunk() {
  int32_t iTotalSize = sizeof(FX_FIXEDSTORECHUNK) + m_iDefChunkSize +
                       m_iBlockSize * m_iDefChunkSize;
  FX_LPFIXEDSTORECHUNK pChunk =
      (FX_LPFIXEDSTORECHUNK)FX_Alloc(uint8_t, iTotalSize);
  if (pChunk == NULL) {
    return NULL;
  }
  FXSYS_memset(pChunk->FirstFlag(), 0, m_iDefChunkSize);
  pChunk->pNextChunk = m_pChunk;
  pChunk->iChunkSize = m_iDefChunkSize;
  pChunk->iFreeNum = m_iDefChunkSize;
  m_pChunk = pChunk;
  return pChunk;
}
void* CFX_FixedStore::Alloc(size_t size) {
  if (size > m_iBlockSize) {
    return NULL;
  }
  FX_LPFIXEDSTORECHUNK pChunk = m_pChunk;
  while (pChunk != NULL) {
    if (pChunk->iFreeNum > 0) {
      break;
    }
    pChunk = pChunk->pNextChunk;
  }
  if (pChunk == NULL) {
    pChunk = AllocChunk();
  }
  FXSYS_assert(pChunk != NULL);
  uint8_t* pFlags = pChunk->FirstFlag();
  size_t i = 0;
  for (; i < pChunk->iChunkSize; i++)
    if (pFlags[i] == 0) {
      break;
    }
  FXSYS_assert(i < pChunk->iChunkSize);
  pFlags[i] = 1;
  pChunk->iFreeNum--;
  return pChunk->FirstBlock() + i * m_iBlockSize;
}
void CFX_FixedStore::Free(void* pBlock) {
  FXSYS_assert(pBlock != NULL);
  FX_LPFIXEDSTORECHUNK pPrior, pChunk;
  pPrior = NULL, pChunk = m_pChunk;
  uint8_t* pStart = NULL;
  uint8_t* pEnd;
  while (pChunk != NULL) {
    pStart = pChunk->FirstBlock();
    if (pBlock >= pStart) {
      pEnd = pStart + m_iBlockSize * pChunk->iChunkSize;
      if (pBlock < pEnd) {
        break;
      }
    }
    pPrior = pChunk, pChunk = pChunk->pNextChunk;
  }
  FXSYS_assert(pChunk != NULL);
  size_t iPos = ((uint8_t*)pBlock - pStart) / m_iBlockSize;
  FXSYS_assert(iPos < pChunk->iChunkSize);
  uint8_t* pFlags = pChunk->FirstFlag();
  if (pFlags[iPos] == 0) {
    return;
  }
  pFlags[iPos] = 0;
  pChunk->iFreeNum++;
  if (pChunk->iFreeNum == pChunk->iChunkSize) {
    if (pPrior == NULL) {
      m_pChunk = pChunk->pNextChunk;
    } else {
      pPrior->pNextChunk = pChunk->pNextChunk;
    }
    FX_Free(pChunk);
  }
}
size_t CFX_FixedStore::SetDefChunkSize(size_t iChunkSize) {
  FXSYS_assert(iChunkSize != 0);
  size_t v = m_iDefChunkSize;
  m_iDefChunkSize = FX_4BYTEALIGN(iChunkSize);
  return v;
}
#ifndef _FXEMB
CFX_DynamicStore::CFX_DynamicStore(size_t iDefChunkSize)
    : m_iDefChunkSize(iDefChunkSize), m_pChunk(NULL) {
  FXSYS_assert(m_iDefChunkSize != 0);
}
CFX_DynamicStore::~CFX_DynamicStore() {
  FX_LPDYNAMICSTORECHUNK pChunk, pNext;
  pChunk = m_pChunk;
  while (pChunk != NULL) {
    pNext = pChunk->pNextChunk;
    FX_Free(pChunk);
    pChunk = pNext;
  }
}
FX_LPDYNAMICSTORECHUNK CFX_DynamicStore::AllocChunk(size_t size) {
  FXSYS_assert(size != 0);
  FX_LPDYNAMICSTORECHUNK pChunk = (FX_LPDYNAMICSTORECHUNK)FX_Alloc(
      uint8_t,
      sizeof(FX_DYNAMICSTORECHUNK) + sizeof(FX_DYNAMICSTOREBLOCK) * 2 + size);
  if (pChunk == NULL) {
    return NULL;
  }
  pChunk->iChunkSize = size;
  pChunk->iFreeSize = size;
  FX_LPDYNAMICSTOREBLOCK pBlock = pChunk->FirstBlock();
  pBlock->iBlockSize = size;
  pBlock->bUsed = FALSE;
  pBlock = pBlock->NextBlock();
  pBlock->iBlockSize = 0;
  pBlock->bUsed = TRUE;
  if (m_pChunk != NULL && size >= m_iDefChunkSize) {
    FX_LPDYNAMICSTORECHUNK pLast = m_pChunk;
    while (pLast->pNextChunk != NULL) {
      pLast = pLast->pNextChunk;
    }
    pLast->pNextChunk = pChunk;
    pChunk->pNextChunk = NULL;
  } else {
    pChunk->pNextChunk = m_pChunk;
    m_pChunk = pChunk;
  }
  return pChunk;
}
void* CFX_DynamicStore::Alloc(size_t size) {
  size = FX_4BYTEALIGN(size);
  FXSYS_assert(size != 0);
  FX_LPDYNAMICSTORECHUNK pChunk = m_pChunk;
  FX_LPDYNAMICSTOREBLOCK pBlock = NULL;
  while (pChunk != NULL) {
    if (pChunk->iFreeSize >= size) {
      pBlock = pChunk->FirstBlock();
      FX_BOOL bFind = FALSE;
      while (pBlock->iBlockSize != 0) {
        if (!pBlock->bUsed && pBlock->iBlockSize >= size) {
          bFind = TRUE;
          break;
        }
        pBlock = pBlock->NextBlock();
      }
      if (bFind) {
        break;
      }
    }
    pChunk = pChunk->pNextChunk;
  }
  if (pChunk == NULL) {
    pChunk = AllocChunk(std::max(m_iDefChunkSize, size));
    pBlock = pChunk->FirstBlock();
  }
  FXSYS_assert(pChunk != NULL && pBlock != NULL);
  size_t m = size + sizeof(FX_DYNAMICSTOREBLOCK);
  pBlock->bUsed = TRUE;
  if (pBlock->iBlockSize > m) {
    size_t n = pBlock->iBlockSize;
    pBlock->iBlockSize = size;
    FX_LPDYNAMICSTOREBLOCK pNextBlock = pBlock->NextBlock();
    pNextBlock->bUsed = FALSE;
    pNextBlock->iBlockSize = n - size - sizeof(FX_DYNAMICSTOREBLOCK);
    pChunk->iFreeSize -= size + sizeof(FX_DYNAMICSTOREBLOCK);
  } else {
    pChunk->iFreeSize -= pBlock->iBlockSize;
  }
  return pBlock->Data();
}
void CFX_DynamicStore::Free(void* pBlock) {
  FXSYS_assert(pBlock != NULL);
  FX_LPDYNAMICSTORECHUNK pPriorChunk, pChunk;
  pPriorChunk = NULL, pChunk = m_pChunk;
  while (pChunk != NULL) {
    if (pBlock > pChunk &&
        pBlock <= ((uint8_t*)pChunk + sizeof(FX_DYNAMICSTORECHUNK) +
                   pChunk->iChunkSize)) {
      break;
    }
    pPriorChunk = pChunk, pChunk = pChunk->pNextChunk;
  }
  FXSYS_assert(pChunk != NULL);
  FX_LPDYNAMICSTOREBLOCK pPriorBlock, pFindBlock;
  pPriorBlock = NULL, pFindBlock = pChunk->FirstBlock();
  while (pFindBlock->iBlockSize != 0) {
    if (pBlock == (void*)pFindBlock->Data()) {
      break;
    }
    pPriorBlock = pFindBlock;
    pFindBlock = pFindBlock->NextBlock();
  }
  FXSYS_assert(pFindBlock->iBlockSize != 0 && pFindBlock->bUsed &&
               pBlock == (void*)pFindBlock->Data());
  pFindBlock->bUsed = FALSE;
  pChunk->iFreeSize += pFindBlock->iBlockSize;
  if (pPriorBlock == NULL) {
    pPriorBlock = pChunk->FirstBlock();
  } else if (pPriorBlock->bUsed) {
    pPriorBlock = pFindBlock;
  }
  pFindBlock = pPriorBlock;
  size_t sizeFree = 0;
  size_t sizeBlock = 0;
  while (pFindBlock->iBlockSize != 0 && !pFindBlock->bUsed) {
    if (pFindBlock != pPriorBlock) {
      sizeFree += sizeof(FX_DYNAMICSTOREBLOCK);
      sizeBlock += sizeof(FX_DYNAMICSTOREBLOCK);
    }
    sizeBlock += pFindBlock->iBlockSize;
    pFindBlock = pFindBlock->NextBlock();
  }
  pPriorBlock->iBlockSize = sizeBlock;
  pChunk->iFreeSize += sizeFree;
  if (pChunk->iFreeSize == pChunk->iChunkSize) {
    if (pPriorChunk == NULL) {
      m_pChunk = pChunk->pNextChunk;
    } else {
      pPriorChunk->pNextChunk = pChunk->pNextChunk;
    }
    FX_Free(pChunk);
  }
}
size_t CFX_DynamicStore::SetDefChunkSize(size_t size) {
  FXSYS_assert(size != 0);
  size_t v = m_iDefChunkSize;
  m_iDefChunkSize = size;
  return v;
}
#endif


text:
#ifndef PORTMACRO_H
    #define PORTMACRO_H

/* Hardware specifics. */
    #include <intrinsics.h>

    #ifdef __cplusplus
        extern "C" {
    #endif

/*-----------------------------------------------------------
 * Port specific definitions.
 *
 * The settings in this file configure FreeRTOS correctly for the
 * given hardware and compiler.
 *
 * These settings should not be altered.
 *-----------------------------------------------------------
 */

/* When the FIT configurator or the Smart Configurator is used, platform.h has to be
 * used. */
    #ifndef configINCLUDE_PLATFORM_H_INSTEAD_OF_IODEFINE_H
        #define configINCLUDE_PLATFORM_H_INSTEAD_OF_IODEFINE_H 0
    #endif

/* If configUSE_TASK_DPFPU_SUPPORT is set to 1 (or undefined) then each task will
 * be created without a DPFPU context, and a task must call vTaskUsesDPFPU() before
 * making use of any DPFPU registers.  If configUSE_TASK_DPFPU_SUPPORT is set to 2 then
 * tasks are created with a DPFPU context by default, and calling vTaskUsesDPFPU() has
 * no effect.  If configUSE_TASK_DPFPU_SUPPORT is set to 0 then tasks never take care
 * of any DPFPU context (even if DPFPU registers are used). */
    #ifndef configUSE_TASK_DPFPU_SUPPORT
        #define configUSE_TASK_DPFPU_SUPPORT 1
    #endif

/*-----------------------------------------------------------*/

/* Type definitions - these are a bit legacy and not really used now, other than
 * portSTACK_TYPE and portBASE_TYPE. */
    #define portCHAR          char
    #define portFLOAT         float
    #define portDOUBLE        double
    #define portLONG          long
    #define portSHORT         short
    #define portSTACK_TYPE    uint32_t
    #define portBASE_TYPE     long

    typedef portSTACK_TYPE   StackType_t;
    typedef long             BaseType_t;
    typedef unsigned long    UBaseType_t;

    #if ( configUSE_16_BIT_TICKS == 1 )
        typedef uint16_t     TickType_t;
        #define portMAX_DELAY              ( TickType_t ) 0xffff
    #else
        typedef uint32_t     TickType_t;
        #define portMAX_DELAY              ( TickType_t ) 0xffffffffUL

/* 32-bit tick type on a 32-bit architecture, so reads of the tick count do
 * not need to be guarded with a critical section. */
        #define portTICK_TYPE_IS_ATOMIC    1
    #endif

/*-----------------------------------------------------------*/

/* Hardware specifics. */
    #define portBYTE_ALIGNMENT    8     /* Could make four, according to manual. */
    #define portSTACK_GROWTH      -1
    #define portTICK_PERIOD_MS    ( ( TickType_t ) 1000 / configTICK_RATE_HZ )
    #define portNOP()    __no_operation()

/* Yield equivalent to "*portITU_SWINTR = 0x01; ( void ) *portITU_SWINTR;"
 * where portITU_SWINTR is the location of the software interrupt register
 * (0x000872E0).  Don't rely on the assembler to select a register, so instead
 * save and restore clobbered registers manually. */
    #define portYIELD()           \
    __asm volatile                \
    (                             \
        "PUSH.L	R10					\n"\
        "MOV.L	#0x872E0, R10		\n"\
        "MOV.B	#0x1, [R10]			\n"\
        "CMP	[R10].UB, R10		\n"\
        "POP    R10					\n"\
        portCDT_NO_PARSE( ::: ) "cc"\
    )

    #define portYIELD_FROM_ISR( x )                           do { if( ( x ) != pdFALSE ) portYIELD(); } while( 0 )

/* Workaround to reduce errors/warnings caused by e2 studio CDT's INDEXER and CODAN. */
    #ifdef __CDT_PARSER__
    #ifndef __asm
    #define __asm asm
    #endif
    #ifndef __attribute__
    #define __attribute__( ... )
    #endif
    #define portCDT_NO_PARSE( token )
    #else
    #define portCDT_NO_PARSE( token ) token
    #endif

/* These macros should not be called directly, but through the
 * taskENTER_CRITICAL() and taskEXIT_CRITICAL() macros.  An extra check is
 * performed if configASSERT() is defined to ensure an assertion handler does not
 * inadvertently attempt to lower the IPL when the call to assert was triggered
 * because the IPL value was found to be above	configMAX_SYSCALL_INTERRUPT_PRIORITY
 * when an ISR safe FreeRTOS API function was executed.  ISR safe FreeRTOS API
 * functions are those that end in FromISR.  FreeRTOS maintains a separate
 * interrupt API to ensure API function and interrupt entry is as fast and as
 * simple as possible. */
    #define portENABLE_INTERRUPTS()                           __set_interrupt_level( ( uint8_t ) 0 )
    #ifdef configASSERT
        #define portASSERT_IF_INTERRUPT_PRIORITY_INVALID()    configASSERT( ( __get_interrupt_level() <= configMAX_SYSCALL_INTERRUPT_PRIORITY ) )
        #define portDISABLE_INTERRUPTS()                      if( __get_interrupt_level() < configMAX_SYSCALL_INTERRUPT_PRIORITY ) __set_interrupt_level( ( uint8_t ) configMAX_SYSCALL_INTERRUPT_PRIORITY )
    #else
        #define portDISABLE_INTERRUPTS()                      __set_interrupt_level( ( uint8_t ) configMAX_SYSCALL_INTERRUPT_PRIORITY )
    #endif

/* Critical nesting counts are stored in the TCB. */
    #define portCRITICAL_NESTING_IN_TCB    ( 1 )

/* The critical nesting functions defined within tasks.c. */
    extern void vTaskEnterCritical( void );
    extern void vTaskExitCritical( void );
    #define portENTER_CRITICAL()    vTaskEnterCritical()
    #define portEXIT_CRITICAL()     vTaskExitCritical()

/* As this port allows interrupt nesting... */
    #define portSET_INTERRUPT_MASK_FROM_ISR()                              __get_interrupt_level(); portDISABLE_INTERRUPTS()
    #define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus )    __set_interrupt_level( ( uint8_t ) ( uxSavedInterruptStatus ) )

/*-----------------------------------------------------------*/

/* Task function macros as described on the FreeRTOS.org WEB site. */
    #define portTASK_FUNCTION_PROTO( vFunction, pvParameters )    void vFunction( void * pvParameters )
    #define portTASK_FUNCTION( vFunction, pvParameters )          void vFunction( void * pvParameters )

/*-----------------------------------------------------------*/

/* If configUSE_TASK_DPFPU_SUPPORT is set to 1 (or left undefined) then tasks are
 * created without a DPFPU context and must call vPortTaskUsesDPFPU() to give
 * themselves a DPFPU context before using any DPFPU instructions.  If
 * configUSE_TASK_DPFPU_SUPPORT is set to 2 then all tasks will have a DPFPU context
 * by default. */
    #if( configUSE_TASK_DPFPU_SUPPORT == 1 )
        void vPortTaskUsesDPFPU( void );
    #else
/* Each task has a DPFPU context already, so define this function away to
 * nothing to prevent it being called accidentally. */
        #define vPortTaskUsesDPFPU()
    #endif
    #define portTASK_USES_DPFPU() vPortTaskUsesDPFPU()

/* Definition to allow compatibility with existing FreeRTOS Demo using flop.c. */
    #define portTASK_USES_FLOATING_POINT() vPortTaskUsesDPFPU()

/* Prevent warnings of undefined behaviour: the order of volatile accesses is
 * undefined - all warnings have been manually checked and are not an issue, and
 * the warnings cannot be prevent by code changes without undesirable effects. */
    #pragma diag_suppress=Pa082

    #ifdef __cplusplus
        }
    #endif

#endif /* PORTMACRO_H */


text:
layout: post
title: Permission denied
---

After setting up hadoop cluster when I started first time, I was getting following error

ERROR org.apache.hadoop.security.UserGroupInformation: PriviledgedActionException as:root cause:org.apache.hadoop.security.AccessControlException: Permission denied: user=root, access=WRITE, inode="small":root:supergroup:rwxr-xr-x

#Resolution:

The exception was thrown because root user did not had permissions on target direcory "small" which was in hdfs
I had to change permissions for that directory through hadoop command

hadoop fs -mkdir /data/small

hadoop fs -chown root:root /data/small

if you are running as any other user than root, you might need to use following commands

sudo -su root hadoop fs -mkdir /data/small

sudo -su root hadoop fs -chown username:grpname /data/small


text:
<?php

namespace Bixie\PkFramework\FieldType\Upload;

use Bixie\PkFramework\FieldType\FieldTypeUpload;

class UploadFieldType extends FieldTypeUpload {

}


text:
/*
    Do Programming Exercise 7, but use "new" to allocate a structure instead of declaring
    a structure variable. Also have the program request the pizza diameter before it
    requests the pizza company name.
*/

#include <iostream>
using namespace std;

struct Pizza {
    char name[80];
    int diameter;
    int weight;
};

int main()
{
    Pizza * pizza = new Pizza;

    cout << "Diameter (in cm): ";
    (cin >> pizza->diameter).get(); // cin.get() removes '\n' after "cin >>"

    cout << "Name: ";
    cin.getline(pizza->name, sizeof(pizza->name)); // also removes '\n' from the stream

    cout << "Weight (in grams): ";
    cin >> pizza->weight; // also leaves '\n' in the stream
    cin.get();

    cout << endl << "Let's see what we've got here ..." << endl;
    cout << "Pizza name: " << pizza->name << endl;
    cout << "Pizza diameter: " << pizza->diameter << " cm" << endl;
    cout << "Pizza weight: " << pizza->weight << " grams" << endl;

    delete pizza;
}


text:
package grails.util;

import groovy.lang.Closure;
import groovy.lang.GroovyObjectSupport;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * A simple class that takes method invocations and property setters and populates
 * the arguments of these into the supplied map ignoring null values.
 *
 * @author Graeme Rocher
 * @since 1.2
 */
@SuppressWarnings({"unchecked","rawtypes"})
public class ClosureToMapPopulator extends GroovyObjectSupport {

    private Map map;

    public ClosureToMapPopulator(Map theMap) {
        map = theMap;
    }

    public ClosureToMapPopulator() {
        this(new HashMap());
    }

    public Map populate(Closure callable) {
        callable.setDelegate(this);
        callable.setResolveStrategy(Closure.DELEGATE_FIRST);
        callable.call();
        return map;
    }

    @Override
    public void setProperty(String name, Object o) {
        if (o != null) {
            map.put(name, o);
        }
    }

    @Override
    public Object invokeMethod(String name, Object o) {
        if (o != null) {
            if (o.getClass().isArray()) {
                Object[] args = (Object[])o;
                if (args.length == 1) {
                    map.put(name, args[0]);
                }
                else {
                    map.put(name, Arrays.asList(args));
                }
            }
            else {
                map.put(name,o);
            }
        }
        return null;
    }
}


text:
"use strict";
var strTools = require('../../../tools/str');

var Sequence = function (block) {
	this.block = block;

	this.generator = this.block.generator;
	this.options = this.block.options;

	this.isOpen = false;
	this.lastCtx = null;
};

Sequence.prototype.open = function () {
	var indent = this.options.indentStr;

	this.block.buffer.push(
		indent, this.options.thisAlias, '.', this.options.funcStrs.append, '(\n',
		indent, indent
	);

	this.isOpen = true;
};

Sequence.prototype.separate = function () {
	var buffer = this.block.buffer;

	buffer.push(',');

	if (this.lastCtx) {
		this.generator.appendLineNumber(this.lastCtx, buffer);
	}

	buffer.push(
		'\n',
		this.options.indentStr, this.options.indentStr
	);
};

Sequence.prototype.close = function (ctx) {
	if (this.isOpen) {
		var buffer = this.block.buffer;

		if (this.lastCtx) {
			this.generator.appendLineNumber(this.lastCtx, buffer);
		}

		buffer.push(
			'\n',
			this.options.indentStr, ');'
		);

		if (this.options.appendLineNumbersFor.sequenceClose) {
			this.generator.appendLineNumber(ctx, buffer);
		}

		buffer.push('\n');

		this.isOpen = false;
	}
};

Sequence.prototype.openOrSeparateIfNeed = function () {
	if (!this.isOpen) {
		this.open();
	}
	else {
		this.separate();
	}
};

Sequence.prototype.updateLastCtx = function (ctx, lineNumbersAllowed) {
	if (lineNumbersAllowed) {
		this.lastCtx = ctx;
	}
	else {
		this.lastCtx = null;
	}
};

// within sequence tokens

Sequence.prototype.onFragmentToken = function (token) {
	this.appendFragment(token);
};

Sequence.prototype.onExpressionToken = function (token) {
	this.appendExpression(token);
};

Sequence.prototype.onCssToken = function (token) {
	this.appendCssName(token);
};

Sequence.prototype.onSpaceToken = function (token) {
	this.appendSpace(token);
};

// append for tokens

Sequence.prototype.appendFragment = function (token) {
	var fragment = token.fragment;

	if (this.options.needCompactFragmentWhitespaces) {
		fragment = this.compactFragmentWhitespaces(fragment);
	}

	if (fragment) {
		this.openOrSeparateIfNeed();
		this.block.buffer.push("'", this.jsStringEscape(fragment), "'");
		this.updateLastCtx(token.ctx, this.options.appendLineNumbersFor.fragment);
	}
};

Sequence.prototype.appendExpression = function (token) {
	var expression = token.expression;

	if (expression.search(/[\r\n]/) == -1) {
		expression = expression.trim();
	}

	this.openOrSeparateIfNeed();
	if (token.toBeEscaped) {
		this.block.buffer.push(
			this.options.thisAlias, '.',
			this.options.funcStrs.escape, '(', expression, ')'
		);
	}
	else {
		this.block.buffer.push(expression);
	}

	this.updateLastCtx(token.ctx, this.options.appendLineNumbersFor.expression);
};

Sequence.prototype.appendCssName = function (token) {
	this.openOrSeparateIfNeed();

	var buffer = this.block.buffer;

	if (token.nameExpr == null && token.nameStr == null && token.modifiers == null) {
		buffer.push(this.options.thisAlias, '.', this.options.css.baseCssNamePropStr);
	}
	else if (this.options.css.appendCssNamesLiterallyWhenPossible && token.nameStr != null) {
		buffer.push('\'', this.jsStringEscape(token.nameStr.trim()), '\'');
	}
	else {
		if (!this.options.css.getCssNameFuncIsGlobal) {
			buffer.push(this.options.thisAlias, '.');
		}

		buffer.push(this.options.css.getCssNameFuncStr, '(');

		if (token.nameStr != null) {
			buffer.push('\'', this.jsStringEscape(token.nameStr.trim()), '\'');
		}
		else {
			if (token.nameExpr == null) {
				var useTypeHint = this.options.css.baseCssNamePropUseTypeHint;
				if (useTypeHint) {
					buffer.push('/** @type {string} */ (');
				}
				buffer.push(this.options.thisAlias, '.', this.options.css.baseCssNamePropStr);
				if (useTypeHint) {
					buffer.push(')');
				}
			}
			else {
				buffer.push(token.nameExpr.trim());
			}
			buffer.push(', \'', this.jsStringEscape(token.modifiers.trim()), '\'');
		}

		buffer.push(')');
	}

	this.updateLastCtx(token.ctx, this.options.appendLineNumbersFor.expression);
};

Sequence.prototype.appendSpace = function (token) {
	this.openOrSeparateIfNeed();
	this.block.buffer.push("' '");
	this.updateLastCtx(token.ctx, this.options.appendLineNumbersFor.fragment);
};

// string utilities

Sequence.prototype.compactFragmentWhitespaces = function (fragment) {
	// NOTE keep in mind that html can contain not only text and tags but also script blocks
	return fragment
		.replace(/\s*[\r\n]+\s*</g, '<')
		.replace(/>\s*[\r\n]+\s*/g, '>')
		.replace(/(^\s*[\r\n]\s*)|(\s*[\r\n]\s*$)/g, '');
};

Sequence.prototype.jsStringEscape = function (str) {
	return strTools.jsStringEscape(str);
};

module.exports = Sequence;