text:
layout: post
disqus_identifier: #18
comments: true
categories:
   - .NET
   - Android
   - C#
   - Shopping Cart
   - Windows Phone 8
   - XF
   - Xamarin
   - iOS
title: "Xamarin.Froms: Frames, Event Handlers, and Binding Bugs"
---

To recap, I'm writing a shopping cart app for Windows Phone, Android, and iOS.  The purpose of the app is primarily to let me use Forms.  Each post will build on top of the previous one.

Last time I got some basic binding setup and navigation working.  Today I plan on cleaning up the views a bit so that they look "nice".  Well nicer.  After that I'd like to show a list of products and let the user drill in and look at details.

## Recap and Code
This is the third post in the series, you can find the rest here:

* Day 0:  Getting Started ([blog](/archive/2014/07/22/xamarin-forms-shopping-cart-day-0/) / [code](https://github.com/jquintus/ShoppingCartXF/raw/master/Archive/ShoppingCart-Day0.zip))
* Day 1:  Binding and Navigation ([blog](/archive/2014/08/02/xf-day-1/) / [code](https://github.com/jquintus/ShoppingCartXF/tree/ShoppingCart-Day1))
* **Day 2:  Frames, Event Handlers, and Binding Bugs** ([blog](/archive/2014/08/11/xf-day-2/) / [code](https://github.com/jquintus/ShoppingCartXF/tree/ShoppingCart-Day2))

The latest version of the code can always be accessed on the [GitHub project page](https://github.com/jquintus/ShoppingCartXF/).

## Cleaning up Login and Main Page
Last time I was focused on functionality.  I was happy to just get the pages to do what I want. Now i want to take a little time and play with the layout a bit.  First on the docket is "MainPage".  It really isn't the main page, so I'll rename that to "WelcomePage".  This includes the the view model as well.

With that done I want to add some space around all of the text box and button.  Problem is: there's no "margin" property on any of the controls.  After a little digging, it seems that the only way to add spacing is to wrap each control in its own [ContentView](http://androidapi.xamarin.com/?link=T%3aXamarin.Forms.ContentView) and set the Padding property on that.  A slightly simpler approach is to use a [Frame](http://androidapi.xamarin.com/?link=T%3aXamarin.Forms.Frame) instead.  It inherits directly from ContentView and has a default padding of 20.  Despite the fact that this only saves me from setting one property, the fact that it's in a Frame helps me remember why I'm wrapping the control in the first place.  Let's wait a few weeks and see if I continue using Frames.

The WelcomePage (né MainPage) now looks like this:

```xml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ShoppingCart.Views.WelcomePage"
             xmlns:local="clr-namespace:ShoppingCart;assembly=ShoppingCart"
             BindingContext="{x:Static local:App.WelcomeViewModel}">

  <StackLayout
    VerticalOptions="Center">
    <Frame>
      <Label Text="Welcome to The Store" Font="Bold, Large" HorizontalOptions="Center" />
    </Frame>

    <Label Text="Login to start shopping" HorizontalOptions="Center" />

    <Frame>
      <Button Text ="Log In" Command="{Binding GoToLoginPageCommand}" HorizontalOptions="Center" />
    </Frame>
  </StackLayout>
</ContentPage>
```

I also tweaked the welcome text making it bigger and bold as well as adding a call to action to help the user navigate to their next step.  There's a fair bit you can do with the Font (size, style) property just by providing a comma separated list of values.

The login page got the same spacing treatment, including a nice fat margin around the entire page just so the text boxes don't sit flush against the right side.  It's still a little stark so I'll throw in a touch of color on the title text, just because I can.

```xml
<StackLayout VerticalOptions="FillAndExpand" Padding="50">

<Frame Padding="75">
  <Label Text="Login"
    Font="Bold,Large"
    TextColor="Yellow"
    HorizontalOptions="Center" />
</Frame>

<Label Text="User name"
  HorizontalOptions="Start" />
<Entry Text ="{Binding Username}"
  Placeholder ="User name goes here"
  HorizontalOptions="FillAndExpand" />

<Label Text="Password"
  HorizontalOptions="Start" />
<Entry Text ="{Binding Password}"
  Placeholder ="Password goes here"
  HorizontalOptions="FillAndExpand" />

<Button Text ="Log In"
  Command="{Binding LoginCommand}"
  HorizontalOptions="CenterAndExpand" />

</StackLayout>
```

Now that looks a little bit nicer.

![](/images/posts/2014/2014-08-11-xf-day-2/image.png)

## Data

Now that the two pages I have look reasonable, I'll add another.  In order to show some data, I actually need data.  To keep it simple, I start off by creating a list of hard coded C# data.  I have to admit that I got a bit silly here.  At first I tried to hand craft a back log of data.  That got old really fast.  In fact I only got one item defined before I realized I was wasting a lot of time.  Next I decided to grab a list of products (books) from the web and just tweak the data to my needs.  This too proved onerous.  Then I broke down and went to the web to generate all of my data.  I found a [great site](http://www.generatedata.com/) that even outputs the data in JSON.  It was the first hit on Google.  To process the JSON i nuget and install [Newtonsoft's Json.NET](https://www.nuget.org/packages/newtonsoft.json/).

I add a ProductLoader and a ProductService class.  The loader simply stores the literal string of JSON and deserializes it on request.  In the future I want to create another implementation that reads the data from disk or the web.  The ProductService doesn't care where the data comes from, it provides the view models with an interface to query and filter the data.  Because the underlying data will eventually come from a web request, both of these services asynchronously return Tasks. I use Stephen Cleary's [NotifyTaskCompletion](http://msdn.microsoft.com/en-us/magazine/dn605875.aspx) in my view model to consume these services.  For a detailed explanation of what's going on here, take a look at his [Patterns for Asynchronous MVVM Applications](http://msdn.microsoft.com/en-us/magazine/dn605875.aspx) series.

The data object itself is pretty simple.

```csharp
public class Item
{
    public string Category { get; set; }
    public string Description { get; set; }
    public string ImageUrl { get; set; }
    public string Name { get; set; }
    public double Price { get; set; }
    public string ProductCode { get; set; }
    public int Rating { get; set; }
    public List<string> Tags { get; set; }
}
```

The Category property lets us show a short list to the user once they log in.  Once they pick a category they see all of the items in that category and then drill down into a specific item.  To accommodate this flow, I'll add three more pages with corresponding view models:

* CategoriesListPage/ViewModel
* ProductsListPage/ViewModel
* ProductPage/ViewModel

With a bigger app I'd lean towards single instances of each of these pages and using a message broker to update one from the other.  I..e, when a category is clicked on in the CategoriesList page I'd send an "Update List of Products" message and then navigate to the ProductsPage.  But since I already have the convenient App.cs handling all of my interactions between pages, I'll just squash it into there.  Not ideal for a larger app that I'd like to keep decoupled, but fine for the five pages I currently have.

## Lists and DataTemplates

The first thing to tackle is to show the list of categories.  This is similar to traditional two step process in Windows XAML.  Step one:  bind the ItemsSource property to the list.  A quick reminder that the Categories property is a [NotifyTaskCompletion<List<string>>](http://msdn.microsoft.com/en-us/magazine/dn605875.aspx) which means I need to bind against Categories.Result.  Step two:  define a data template to define how each row looks.  Strictly speaking, since my underlying data is a string, I can skip this step.  Since this is my first time defining a data template in XF, I'll define one anyway just to make sure it works how I expect.  In my example I'm making the background color red just so I can verify that it's using my DataTemplate.

```xml
<ListView ItemsSource="{Binding Categories.Result}" ItemSelected="OnItemSelected">
   <ListView.ItemTemplate>
      <DataTemplate>
         <ViewCell>
            <Label Text="{Binding .}" BackgroundColor = "Red" YAlign="Center" Font="Medium" />
         </ViewCell>
      </DataTemplate>
   </ListView.ItemTemplate>
</ListView>
```

## Handling Events

You'll notice in the above definition of my ListView that I'm setting the ItemsSelected event handler.  I'm not binding against the view model here, I'm calling into code behind which then calls into my view model.

```csharp
public partial class CategoriesListPage
{
    public CategoriesListPage()
    {
        InitializeComponent();
    }

    private void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        var param = e.SelectedItem as string;
        var command = ((CategoriesListViewModel)BindingContext).NavigateToCategory;

        if (command.CanExecute(param))
        {
            command.Execute(param);
        }
    }
}
```

This is a lot of boilerplate code for handling a click.  The problem is that the ListView doesn't expose a command I can bind against when an item is selected.  In a traditional Xaml app I'd use the EventToCommand pattern except that it is built on [Blend behaviors](http://wpftutorial.net/Behaviors.html) which aren't PCL compatible and therefore not Xamarin compatible.

Another option was to subclass the ListView class and expose the command logic that I need.  I might eventually go this route, but I'll probably need more than a few list boxes in my app to justify it.

## Binding Bug in XF

The command for navigating to a category's page gets a list of all the items for that category and calls into the static App class to get the page to navigate to.

```csharp
var page = App.GetProductsListPage(items, categoryName);
await _navi.PushAsync(page);
```

Originally App.cs just updated the properties on the view model and returned the single instance of the ProductsListPage.

```csharp
public static Page ProductsListPage { get; private set; }

public static Page GetProductsListPage(List<Item> items, string title)
{
    if (string.IsNullOrWhiteSpace(title)) title = "Products";

    ProductsListViewModel.Products = items;
    ProductsListViewModel.Title = title;
    return ProductsListPage;
}
```

This relies on the binding to update the view when something has changed and INotifyProperty.PropertyChanged is raised.  The first time this is called it works just fine.  It fails on all subsequent calls.  After a lot of debugging and assuming that I was wrong I found a recent post on Xamarin's forums explaining that there is a [bug where the UI is not updated when a bound value is changed](http://forums.xamarin.com/discussion/19989/xamarin-forms-ui-not-properly-updated-when-binding-source-value-changed).  Note that this only effects values that are updated in the view model updating on the view; the other way works just fine.  Updating a value in the view (like a text entry) correctly updates the bound value in the view model.  This is why my login page worked just fine.

Xamarin has released a fix for this bug, but as of writing this it is in a pre build of XF.  I tried to use it but kept getting runtime DLL errors.  I tried several times before having to give up on this as an immediate solution.  I will say that this may have just been an issue with user error since it was close to 1 AM at this point.

In my specific case, there was no reason that I had to reuse the same view.  Simply recreating the view every time I wanted to display it was simple enough.

```csharp
public static Page GetProductsListPage(List<Item> items, string title)
{
    if (string.IsNullOrWhiteSpace(title)) title = "Products";

    ProductsListViewModel.Products = items;
    ProductsListViewModel.Title = title;
}
```

## Summary

Today I was able to clean up some of the views using the [Frame](http://androidapi.xamarin.com/?link=T%3aXamarin.Forms.Frame) control to provide margins.  I had to resort to two workarounds, one for routing events to commands in code behind the other for updating the view when a bound value has changed.

I'm not sure what I want to tackle next week.  Perhaps reading from the file stream?  Maybe fleshing out the products view a bit so I display an image to go with the product?

Until then, happy coding.

_this post was originally on the [MasterDevs Blog](http://blog.masterdevs.com/xf-day-2/)_


text:
from __future__ import unicode_literals

from .cases import StaticFilesTestCase

class TestTemplateTag(StaticFilesTestCase):

    def test_template_tag(self):
        self.assertStaticRenders("does/not/exist.png", "/static/does/not/exist.png")
        self.assertStaticRenders("testfile.txt", "/static/testfile.txt")
        self.assertStaticRenders("test.html?foo=1&bar=2", "/static/test.html?foo=1&bar=2", autoescape=False)
        self.assertStaticRenders("test.html?foo=1&bar=2", "/static/test.html?foo=1&bar=2", autoescape=True)

redpajama_set_name: RedPajamaGithub


text:
GnomePackage ('librsvg', version_major = '2.35', version_minor = '0',
        configure_flags = [ '--disable-Bsymbolic' ])


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Description of Due
 *
 * @author MD. Mashfiq
 */
class Due extends CI_Controller {

    function __construct() {
        parent::__construct();
        date_default_timezone_set('Asia/Dhaka');
        $this->load->library('tank_auth');
        if (!$this->tank_auth->is_logged_in()) {         //not logged in
            redirect('login');
            return 0;
        }
        $this->load->library('grocery_CRUD');
        $this->load->model('Due_model');
        $this->load->model('Common');
        $this->load->model('Bank_model');
        $this->load->model('User_access_model');
        $this->User_access_model->check_user_access(5);
    }

    function index() {
        $this->customer_due();
    }

    function customer_due() {
        $crud = new grocery_CRUD();
        $crud->set_table('customer_due')->set_subject('Customer Due')
                ->display_as('id_customer', 'Customer Name')->set_relation('id_customer', 'customer', 'name')
                ->unset_edit()->unset_delete()->unset_add()->unset_read()
                ->columns('Customer ID', 'id_customer', 'total_due_billed', 'total_paid', 'total_due')
                ->callback_column('Customer ID', function ($value, $row) {
                    return $row->id_customer;
                })->add_action('Add payment', base_url() . "asset/img/button/add payment btn.png", '#', '', function ($primary_key, $row) {
            if ($row->total_due > 0) {
                return site_url('due/make_payment/' . $row->id_customer);
            } else {
                return '#';
            }
        });

        $data['customer_id'] = $this->input->get('customer');
        if ($data['customer_id'] != '') {
            $data['customer_dues'] = $this->Due_model->get_customer_due_info($data['customer_id']);
        } else {
            $output = $crud->render();
            $data['glosary'] = $output;
        }

//        $data['customers'] = $this->Due_model->get_all_customers();
        $data['customers_dropdown'] = $this->Due_model->due_customer_dropdown();
        $data['theme_asset_url'] = base_url() . $this->config->item('THEME_ASSET');
        $data['base_url'] = base_url();
        $data['Title'] = 'Customer Due';
//        echo '
';print_r($data);exit();
        $this->load->view($this->config->item('ADMIN_THEME') . 'due/customer_due_and_payment', $data);
    }

    function customer_payment() {

        $data['customer_id'] = $this->input->get('customer');
        $data['date_range'] = $this->input->get('date_range');
//        print_r($data);exit();
        $dates = explode(' - ', $data['date_range']);
        if ($data['date_range'] == '') {
            $dates[0] = '';
            $dates[1] = '';
        }
        if ($data['date_range'] != '' || $data['customer_id'] != '') {
            $data['customer_due_payment'] = $this->Due_model->get_customer_due_payment_info($dates[0], $dates[1], $data['customer_id']);
//            print_r($data);
//            exit();
        }
        $crud = new grocery_CRUD();
        $crud->set_table('customer_payment')->display_as('id_total_sales', 'Memo No')->display_as('id_payment_method','Payment Method')
                ->display_as('id_customer', 'Customer Name')->set_subject('Customer Payment')
                ->set_relation('id_customer', 'customer', 'name')
                ->set_relation('id_payment_method', 'payment_method', 'name_payment_method')
                ->columns('Customer ID', 'id_customer','id_payment_method', 'paid_amount', 'id_total_sales', 'payment_date')
                ->unset_edit()->unset_delete()->unset_add()->unset_read()
                ->callback_column('Customer ID', function ($value, $row) {
                    return $row->id_customer;
                })
                ->where('due_payment_status',1)
                ->order_by('id_customer_payment','desc');
        $output = $crud->render();
        $data['glosary'] = $output;

//        $data['customers'] = $this->Due_model->get_all_customers();
        $data['customers_dropdown'] = $this->Due_model->due_customer_dropdown();
        $data['theme_asset_url'] = base_url() . $this->config->item('THEME_ASSET');
        $data['base_url'] = base_url();
        $data['Title'] = 'Customer Due Payment';
        $this->load->view($this->config->item('ADMIN_THEME') . 'due/customer_due_payment_log', $data);
    }

    function make_payment($customer_id = FALSE) {
        if (!$customer_id) {
            redirect('due/customer_due');
        }
         $this->load->model('misc/Customer_due');
        $data['customer_total_due'] = $this->Customer_due->current_total_due($customer_id);

        $amount = $this->input->post('amount');
        $bank_account_id=$this->input->post('id_account');
        $bank_amount=$this->input->post('bank_payment');
        $bank_check_no=$this->input->post("check_no");

        $total_amount=$amount+$bank_amount;

        $btn=$this->input->post('btn_submit');
        if(isset($btn)){

            if($total_amount > $data['customer_total_due']){
                $data['report_message'] = '
Customer Due is lase then Total Amoutn(Bank+ Cash)
';
            }else{

            $this->load->model('misc/Customer_payment');

                $id_cash=0;
                $id_bank=0;

                if (!empty($amount) && $amount > 0) {

                    $id_cash = $this->Customer_payment->due_payment($customer_id, $amount);

                }
                 if (!empty($bank_amount) && $bank_amount > 0 && !empty($bank_check_no)) {

                    $this->Bank_model->bank_transection($bank_account_id, 1, $bank_amount, $bank_check_no, 1);

                    $id_bank = $this->Customer_payment->due_payment($customer_id, $bank_amount, 3);

                }

                if($id_bank!=0 || $id_cash!=0){

                         $data['due_report_list'] = $this->Customer_payment->generate_due_report($id_cash,$id_bank);
                }else{
                    $data['report_message'] = '
Please Pay Using Cash or Bank otpion Carefully
';
                }
            }

        }

        $data['bank_account_dropdown'] = $this->Bank_model->get_account_dropdown();
        $data['due_detail_table'] = $this->Customer_due->due_detail_table($customer_id);
        $data['customer_name'] = $this->db->select('name')->where('id_customer', $customer_id)->get('customer')->result();
        $data['customer_name'] = $data['customer_name'][0]->name;
        $data['customer_code'] = $customer_id;

//        if ($data['customer_total_due'] < 1) {
//            redirect('due');
//            die();
//        }

        $data['theme_asset_url'] = base_url() . $this->config->item('THEME_ASSET');
        $data['base_url'] = base_url();
        $data['Title'] = 'Make Due Payment';
        $this->load->view($this->config->item('ADMIN_THEME') . 'due/make_payment', $data);
    }

}


text:
window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);

  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };

  return t;
}(document, "script", "twitter-wjs"));

//$.getScript('https://platform.twitter.com/widgets.js', function () {});


text:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
  ~ This is part of Geomajas, a GIS framework, http://www.geomajas.org/.
  ~
  ~ Copyright 2008-2015 Geosparc nv, http://www.geosparc.com/, Belgium.
  ~
  ~ The program is available in open source according to the Apache
  ~ License, Version 2.0. All contributions in this program are covered
  ~ by the Geomajas Contributors License Agreement. For full licensing
  ~ details, see LICENSE.txt in the project root.
  -->

<StyledLayerDescriptor version="1.0.0"
   xsi:schemaLocation="http://www.opengis.net/sld StyledLayerDescriptor.xsd"
   xmlns="http://www.opengis.net/sld"
   xmlns:ogc="http://www.opengis.net/ogc"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

	<NamedLayer>
		<Name>Stacked Point</Name>
		<UserStyle>
			<Name>Stacked Point</Name>
			<IsDefault>1</IsDefault>
			<FeatureTypeStyle>
				<Transformation xmlns:ogc="http://www.opengis.net/ogc">
					<ogc:Function name="vec:PointStacker">
						<ogc:Function name="parameter">
							<ogc:Literal>data</ogc:Literal>
						</ogc:Function>
						<ogc:Function name="parameter">
							<ogc:Literal>cellSize</ogc:Literal>
							<ogc:Literal>30</ogc:Literal>
						</ogc:Function>
						<ogc:Function name="parameter">
							<ogc:Literal>outputBBOX</ogc:Literal>
							<ogc:Function name="env">
								<ogc:Literal>wms_bbox</ogc:Literal>
							</ogc:Function>
						</ogc:Function>
						<ogc:Function name="parameter">
							<ogc:Literal>outputWidth</ogc:Literal>
							<ogc:Function name="env">
								<ogc:Literal>wms_width</ogc:Literal>
							</ogc:Function>
						</ogc:Function>
						<ogc:Function name="parameter">
							<ogc:Literal>outputHeight</ogc:Literal>
							<ogc:Function name="env">
								<ogc:Literal>wms_height</ogc:Literal>
							</ogc:Function>
						</ogc:Function>
					</ogc:Function>
				</Transformation>
				<Rule>
					<Name>main</Name>
					<PointSymbolizer>
						<Graphic>
							<Mark>
								<WellKnownName>ttf://Wingdings#0x68</WellKnownName>
								<Fill>
									<CssParameter name="fill">#66cc00</CssParameter>
								</Fill>
							</Mark>
							<Size>8</Size>
						</Graphic>
					</PointSymbolizer>
				</Rule>
			</FeatureTypeStyle>
		</UserStyle>
	</NamedLayer>

</StyledLayerDescriptor>


text:
<!-- Javascript -->
<!--[if lte IE 8]><script src="/public/javascripts/bind.js"></script><![endif]-->
<script src="/public/javascripts/details.polyfill.js"></script>
<script src="/public/javascripts/jquery-1.11.3.js"></script>
<script src="/public/javascripts/govuk/shim-links-with-button-role.js"></script>
<script src="/public/javascripts/govuk/show-hide-content.js"></script>
<script src="/public/javascripts/application.js"></script>

{% if useAutoStoreData %}
  <script src="/public/javascripts/auto-store-data.js"></script>
{% endif %}

<!-- Validation from https://github.com/abbott567/validation-for-prototypes -->

 <script src="/public/javascripts/validation.js"></script>


text:
from abc import ABCMeta
from unittest import TestCase

from iota import InvalidCommand, StrictIota
from iota.adapter import MockAdapter
from iota.commands import CustomCommand
from iota.commands.core.get_node_info import GetNodeInfoCommand
from test import async_test

class CustomCommandTestCase(TestCase):
    def setUp(self):
        super(CustomCommandTestCase, self).setUp()

        self.name = 'helloWorld'
        self.adapter = MockAdapter()
        self.command = CustomCommand(self.adapter, self.name)

    @async_test
    async def test_call(self):
        """
        Sending a custom command.
        """
        expected_response = {'message': 'Hello, IOTA!'}

        self.adapter.seed_response('helloWorld', expected_response)

        response = await self.command()

        self.assertEqual(response, expected_response)
        self.assertTrue(self.command.called)

        self.assertListEqual(
            self.adapter.requests,
            [{'command': 'helloWorld'}],
        )

    @async_test
    async def test_call_with_parameters(self):
        """
        Sending a custom command with parameters.
        """
        expected_response = {'message': 'Hello, IOTA!'}

        self.adapter.seed_response('helloWorld', expected_response)

        response = await self.command(foo='bar', baz='luhrmann')

        self.assertEqual(response, expected_response)
        self.assertTrue(self.command.called)

        self.assertListEqual(
            self.adapter.requests,
            [{'command': 'helloWorld', 'foo': 'bar', 'baz': 'luhrmann'}],
        )

    @async_test
    async def test_call_error_already_called(self):
        """
        A command can only be called once.
        """
        self.adapter.seed_response('helloWorld', {})
        await self.command()

        with self.assertRaises(RuntimeError):
            await self.command(extra='params')

        self.assertDictEqual(self.command.request, {'command': 'helloWorld'})

    @async_test
    async def test_call_reset(self):
        """
        Resetting a command allows it to be called more than once.
        """
        self.adapter.seed_response('helloWorld', {'message': 'Hello, IOTA!'})
        await self.command()

        self.command.reset()

        self.assertFalse(self.command.called)
        self.assertIsNone(self.command.request)
        self.assertIsNone(self.command.response)

        expected_response = {'message': 'Welcome back!'}
        self.adapter.seed_response('helloWorld', expected_response)
        response = await self.command(foo='bar')

        self.assertDictEqual(response, expected_response)
        self.assertDictEqual(self.command.response, expected_response)

        self.assertDictEqual(
            self.command.request,

            {
                'command': 'helloWorld',
                'foo': 'bar',
            },
        )

class IotaApiTestCase(TestCase):
    def test_init_with_uri(self):
        """
        Passing a URI to the initializer instead of an adapter instance.
        """
        api = StrictIota('mock://')
        self.assertIsInstance(api.adapter, MockAdapter)

    def test_create_command(self):
        """
        Preparing an experimental/undocumented command.
        """
        api = StrictIota(MockAdapter())

        custom_command = api.create_command('helloWorld')

        self.assertIsInstance(custom_command, CustomCommand)
        self.assertEqual(custom_command.command, 'helloWorld')

    def test_use_in_abstract_class(self):
        """
        Tests a regression where adding a client instance to an abstract
        class definition raises an exception.

        References:
            - https://github.com/iotaledger/iota.py/issues/206
        """
        # This statement will raise an exception if the regression is
        # present; no assertions necessary.
        class CustomClient(object, metaclass=ABCMeta):
            client = StrictIota(MockAdapter())


text:
form h3 { margin: 0 0 1em 0; text-align: center; }
form p { margin: 5px auto; }
form p.blabla { margin: 1em 20px 1.5em 20px; font-size: .9em; color: #448; }
form fieldset { margin: 0; margin-top:25px; padding: 0; border: 1px solid #444444; background-color:#F8F8F8; }
form fieldset fieldset { margin: 10px 10px; }
form fieldset legend { margin: 0 20px; padding: 0 10px; font-weight: bold; font-style: italic; font-size: 1.1em; text-shadow: 5px 5px 5px #B9B9B9; }
form fieldset h3 { margin: 0 20px; padding: 0 10px; font-weight: bold; font-style: italic; font-size: 1.1em; text-shadow: 5px 5px 5px #B9B9B9; }
#p_center form fieldset h3 { margin: 5px 20px 10px; padding: 0 10px; font-weight: bold; font-style: italic; font-size: 1.1em; text-shadow: 5px 5px 5px #B9B9B9; }
form span.label { display: block; margin-top: 10px; }
form span.controle { display: block; }
form div.gauche { width: 250px; margin: 0 0 1em 20px; float: left; display: inline; /* évite le Doubled Float-Margin Bug d'IE6 */ }
form div.gauche p { margin: .5em 0; }
form div.gauche span.label { display: block; margin-bottom: .2em; }
form div.gauche label { font-weight: bold; cursor: pointer; }
span.error { background-color:#ff0000; color:#ffffff; display: block; margin-bottom: .2em; }
form div.gauche span.controle { display: block; }
form div.droite { margin: 0 20px 1em 310px; }
form div.droite span.label { display: block; font-weight: bold; }
form div.droite span.controle { display: block; margin: .5em 0 0 30px; }
form div.droite span.controle input.case { position: absolute; margin-left: -30px; }
form div.droite span.controle br { display: none; }
form input[type=text] { width: 95%; border: solid 1px midnightblue; padding: 2px 4px; }
form input[type=password] { width: 95%; border: solid 1px midnightblue; padding: 2px 4px; }
form input.phone_number { width: 68%; border: solid 1px midnightblue; padding: 2px 4px; }
form select { width: 95%; border: solid 1px midnightblue; padding: 2px 4px; }
form select.calling_country_listing { width: 27%; border: solid 1px midnightblue; padding: 2px 4px; }
form input.case { margin-right: 10px; }
form textarea { width: 600px; height: 120px; border: 3px solid #cccccc;	padding: 5px; font-family: Tahoma, sans-serif; }
form p.submit input { width:250px; font:1em Georgia,'Times New Roman',serif; letter-spacing:1; color:#575757; margin:5px 5px 5px 0; }
form .details { font-style:italic; font-size:0.8em; color: #676767; }

/* Services into sliding boxes */
.service_title { display: inline; margin: 0 20px 0 0; padding: 0 10px; font-weight: bold; font-style: normal; font-size: 1.2em; text-shadow: 5px 5px 5px #B9B9B9; }
.rolling_arrow { margin:2px 2px; }

#service_archi_div {  }
#button_service_archi { cursor:pointer; }
#fleche_service_archi {  }
#content_service_archi { display:none; }

#service_joinery_div {  }
#button_service_joinery { cursor:pointer; }
#fleche_service_joinery {  }
#content_service_joinery { display:none; }

#service_garden_div {  }
#button_service_garden { cursor:pointer; }
#fleche_service_garden {  }
#content_service_garden {  }

/* NEW Generation */
.optgroup_1 { margin-top: 10px; margin-bottom: 7px; margin-left: 5px }
.optgroup_2 { margin-top: 10px; margin-bottom: 7px; margin-left: 10px }
.optgroup_3 { margin-top: 10px; margin-bottom: 7px; margin-left: 15px }
.optgroup_title_1 {font-size:130%; margin-bottom: 7px; }
.optgroup_title_2 {font-size:120%; margin-bottom: 7px;}
.optgroup_title_3 {font-size:110%; margin-bottom: 7px;}


text:
        __title__

    __buttons__


text:
package com.microsoft.azure.management.network.v2018_08_01;

import java.util.List;
import com.microsoft.azure.management.network.v2018_08_01.implementation.NetworkInterfaceIPConfigurationInner;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.SubResource;

/**
 * Backend Address Pool of an application gateway.
 */
@JsonFlatten
public class ApplicationGatewayBackendAddressPool extends SubResource {
    /**
     * Collection of references to IPs defined in network interfaces.
     */
    @JsonProperty(value = "properties.backendIPConfigurations")
    private List<NetworkInterfaceIPConfigurationInner> backendIPConfigurations;

    /**
     * Backend addresses.
     */
    @JsonProperty(value = "properties.backendAddresses")
    private List<ApplicationGatewayBackendAddress> backendAddresses;

    /**
     * Provisioning state of the backend address pool resource. Possible values
     * are: 'Updating', 'Deleting', and 'Failed'.
     */
    @JsonProperty(value = "properties.provisioningState")
    private String provisioningState;

    /**
     * Name of the backend address pool that is unique within an Application
     * Gateway.
     */
    @JsonProperty(value = "name")
    private String name;

    /**
     * A unique read-only string that changes whenever the resource is updated.
     */
    @JsonProperty(value = "etag")
    private String etag;

    /**
     * Type of the resource.
     */
    @JsonProperty(value = "type")
    private String type;

    /**
     * Get collection of references to IPs defined in network interfaces.
     *
     * @return the backendIPConfigurations value
     */
    public List<NetworkInterfaceIPConfigurationInner> backendIPConfigurations() {
        return this.backendIPConfigurations;
    }

    /**
     * Set collection of references to IPs defined in network interfaces.
     *
     * @param backendIPConfigurations the backendIPConfigurations value to set
     * @return the ApplicationGatewayBackendAddressPool object itself.
     */
    public ApplicationGatewayBackendAddressPool withBackendIPConfigurations(List<NetworkInterfaceIPConfigurationInner> backendIPConfigurations) {
        this.backendIPConfigurations = backendIPConfigurations;
        return this;
    }

    /**
     * Get backend addresses.
     *
     * @return the backendAddresses value
     */
    public List<ApplicationGatewayBackendAddress> backendAddresses() {
        return this.backendAddresses;
    }

    /**
     * Set backend addresses.
     *
     * @param backendAddresses the backendAddresses value to set
     * @return the ApplicationGatewayBackendAddressPool object itself.
     */
    public ApplicationGatewayBackendAddressPool withBackendAddresses(List<ApplicationGatewayBackendAddress> backendAddresses) {
        this.backendAddresses = backendAddresses;
        return this;
    }

    /**
     * Get provisioning state of the backend address pool resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
     *
     * @return the provisioningState value
     */
    public String provisioningState() {
        return this.provisioningState;
    }

    /**
     * Set provisioning state of the backend address pool resource. Possible values are: 'Updating', 'Deleting', and 'Failed'.
     *
     * @param provisioningState the provisioningState value to set
     * @return the ApplicationGatewayBackendAddressPool object itself.
     */
    public ApplicationGatewayBackendAddressPool withProvisioningState(String provisioningState) {
        this.provisioningState = provisioningState;
        return this;
    }

    /**
     * Get name of the backend address pool that is unique within an Application Gateway.
     *
     * @return the name value
     */
    public String name() {
        return this.name;
    }

    /**
     * Set name of the backend address pool that is unique within an Application Gateway.
     *
     * @param name the name value to set
     * @return the ApplicationGatewayBackendAddressPool object itself.
     */
    public ApplicationGatewayBackendAddressPool withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get a unique read-only string that changes whenever the resource is updated.
     *
     * @return the etag value
     */
    public String etag() {
        return this.etag;
    }

    /**
     * Set a unique read-only string that changes whenever the resource is updated.
     *
     * @param etag the etag value to set
     * @return the ApplicationGatewayBackendAddressPool object itself.
     */
    public ApplicationGatewayBackendAddressPool withEtag(String etag) {
        this.etag = etag;
        return this;
    }

    /**
     * Get type of the resource.
     *
     * @return the type value
     */
    public String type() {
        return this.type;
    }

    /**
     * Set type of the resource.
     *
     * @param type the type value to set
     * @return the ApplicationGatewayBackendAddressPool object itself.
     */
    public ApplicationGatewayBackendAddressPool withType(String type) {
        this.type = type;
        return this;
    }

}


text:
package info.novatec.testit.webtester.browser;

import static info.novatec.testit.webtester.browser.BrowserRegistry.clear;
import static info.novatec.testit.webtester.browser.BrowserRegistry.deregisterBrowser;
import static info.novatec.testit.webtester.browser.BrowserRegistry.executeForAllBrowsers;
import static info.novatec.testit.webtester.browser.BrowserRegistry.lookupBrowser;
import static info.novatec.testit.webtester.browser.BrowserRegistry.registerBrowser;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.openqa.selenium.WebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import info.novatec.testit.webtester.api.browser.Browser;
import info.novatec.testit.webtester.api.callbacks.BrowserCallback;

@RunWith(MockitoJUnitRunner.class)
public class BrowserRegistryTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(BrowserRegistryTest.class);

    private static final long ONE_MILLISECOND = 1L;

    private Browser browser1;
    private Browser browser2;

    private boolean exceptionOccured;

    @Before
    public void setUp() {
        BrowserRegistry.clear();
        browser1 = WebDriverBrowser.forWebDriver(mock(WebDriver.class)).build();
        browser2 = WebDriverBrowser.forWebDriver(mock(WebDriver.class)).build();
    }

    @After
    public void tearDown() {
        BrowserRegistry.clear();
    }

    @Test
    public void testThatRegisteredBrowsersCanBeLookedUp() {

        registerBrowser(browser1);
        registerBrowser(browser2);

        Browser resolved1 = lookupBrowser(browser1.getIdentification());
        Browser resolved2 = lookupBrowser(browser2.getIdentification());

        assertThat(resolved1, is(sameInstance(resolved1)));
        assertThat(resolved2, is(sameInstance(resolved2)));

    }

    @Test
    public void testThatUnregisteredBrowsersCanNoLongerBeLookedUp() {

        registerBrowser(browser1);
        registerBrowser(browser2);
        deregisterBrowser(browser2);

        Browser resolved1 = lookupBrowser(browser1.getIdentification());
        Browser resolved2 = lookupBrowser(browser2.getIdentification());

        assertThat(resolved1, is(sameInstance(resolved1)));
        assertThat(resolved2, is(nullValue()));

    }

    @Test
    public void testThatClearingAllListenersNoLongerNotifiesPreviouslyRegisteredListeners() {

        registerBrowser(browser1);
        registerBrowser(browser2);
        clear();

        Browser resolved1 = lookupBrowser(browser1.getIdentification());
        Browser resolved2 = lookupBrowser(browser2.getIdentification());

        assertThat(resolved1, is(nullValue()));
        assertThat(resolved2, is(nullValue()));

    }

    @Test
    public void testThatCallbacksCanBeExecutedForAllBrowsers() {

        registerBrowser(browser1);
        registerBrowser(browser2);

        BrowserCallback callback = mock(BrowserCallback.class);

        executeForAllBrowsers(callback);

        verify(callback).execute(browser1);
        verify(callback).execute(browser2);

    }

    @Test
    public void testThatExceptionsInCallbackExecutionAreIgnored() {

        BrowserCallback callback = mock(BrowserCallback.class);

        registerBrowser(browser1);
        registerBrowser(browser2);

        doThrow(RuntimeException.class).when(callback).execute(browser1);

        executeForAllBrowsers(callback);

        verify(callback).execute(browser1);
        verify(callback).execute(browser2);

    }

    @Test
    public void testThatConcurrentAddingAndRemovingOfBrowsersWhileExecutingCallbacksDoesNotLeadToConcurrencyIssues()
        throws InterruptedException {

        final BrowserCallback callback = mock(BrowserCallback.class);

        Thread thread1 = createAndStartThread(new Runnable() {

            @Override
            public void run() {
                registerBrowser(browser1);
                deregisterBrowser(browser2);
            }

        });

        Thread thread2 = createAndStartThread(new Runnable() {

            @Override
            public void run() {
                registerBrowser(browser2);
                deregisterBrowser(browser1);
            }

        });

        Thread thread3 = createAndStartThread(new Runnable() {

            @Override
            public void run() {
                clear();
            }

        });

        Thread callbackThread = createAndStartThread(new Runnable() {

            @Override
            public void run() {
                executeForAllBrowsers(callback);
            }

        });

        thread1.join();
        thread2.join();
        thread3.join();
        callbackThread.join();

        assertThat(exceptionOccured, is(false));

    }

    private Thread createAndStartThread(final Runnable runnable) {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    for (int i = 0; i < 100; i++) {
                        Thread.sleep(ONE_MILLISECOND);
                        runnable.run();
                    }
                } catch (Exception e) {
                    reportException(e);
                }
            }

        });
        thread.setDaemon(false);
        thread.start();
        return thread;
    }

    private synchronized void reportException(Throwable e) {
        LOGGER.error("exception", e);
        exceptionOccured = true;
    }

}


text:
title: Polls
---

To add a poll to *any* post, just follow these easy examples:

Borrowed from @codinghorror's [blog post on the same topic][1].

###Single Choice Poll

    [poll]
    - Apples
    - Oranges
    - Pears
    [/poll]

###Multiple Choice Poll

    [poll type=multiple]
    - Apples
    - Oranges
    - Pears
    [/poll]

###Multiple Choice Limited Option Poll

    [poll type=multiple min=1 max=2]
    - Apples
    - Oranges
    - Pears
    [/poll]

###Number Rating Poll

    [poll type=number min=1 max=4]
    [/poll]

###Multiple Polls in one Post
To include several polls in the same post, simply give each poll a name:

    [poll name=fruits]
    - Apples :apple:
    - Oranges :tangerine:
    - Pears :pear:
    [/poll]

  [1]: http://blog.discourse.org/2015/08/improved-polls-in-discourse/

<small class="documentation-source">Source: [https://meta.discourse.org/t/how-to-create-a-poll/34003](https://meta.discourse.org/t/how-to-create-a-poll/34003)</small>


text:
package org.apache.hadoop.security.authorize;

import java.security.Policy;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

/**
 * {@link PolicyProvider} provides the {@link Service} definitions to the
 * security {@link Policy} in effect for Hadoop.
 *
 */
@InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
@InterfaceStability.Evolving
public abstract class PolicyProvider {

  /**
   * Configuration key for the {@link PolicyProvider} implementation.
   */
  public static final String POLICY_PROVIDER_CONFIG =
    "hadoop.security.authorization.policyprovider";

  /**
   * A default {@link PolicyProvider} without any defined services.
   */
  public static final PolicyProvider DEFAULT_POLICY_PROVIDER =
    new PolicyProvider() {
    @Override
    public Service[] getServices() {
      return null;
    }
  };

  /**
   * Get the {@link Service} definitions from the {@link PolicyProvider}.
   * @return the {@link Service} definitions
   */
  public abstract Service[] getServices();
}


text:
const args = require('system').args
const async = require('async')
const page = require('webpage').create()

// Handle HTTP timeouts
page.settings.resourceTimeout = 60 * 1000 // 60 seconds
page.onResourceTimeout = function(request) {
  message = 'Timed out resource at ' + request.url + '. '
  message += 'Code: ' + request.errorCode + '. '
  message += 'Error: ' + request.errorString

  console.log(message)
  phantom.exit(1);
}

function delay(duration, callback) {
  setTimeout(callback, duration)
}

function waitUntil(conditionCallback, done) {
  if (conditionCallback()) {
    done()
  } else {
    delay(10, function() {
      waitUntil(conditionCallback, done)
    })
  }
}

// Rotation by calling the 3D Viewer through the DOM
function rotateY(y) {
  window.viewer.rotate(0, y, 0)
  window.viewer.update()
}

function isLoadingComplete() {
  return page.evaluate(function() {
    return window._loadingComplete
  })
}

function integers(total) {
  const results = []
  for (var i = 0; i < total; i += 1) {
    results.push(i)
  }
  return results
}

function capture(url, tmpDir, total, width, height) {
  const increment = 360 / total

  function imagePath(num) {
    return tmpDir + '/craster-' + num + '.png'
  }

  function rotator(index, callback) {
    const rotation = index * increment
    console.log(index + '/' + total + ': Rotate to ' + rotation)
    page.evaluate(rotateY, increment)
    delay(20, function() {
      page.render(imagePath(index))
      callback()
    })
  }

  function start() {
    console.log('Starting captures in ' + tmpDir + '...')
    page.evaluate(rotateY, 0)
    delay(20, function() {
      async.eachSeries(integers(total), rotator, function() {
        phantom.exit()
      })
    })
  }

  page.viewportSize = { width: width, height: height }
  page.paperSize = { width: width, height: height }
  page.clipRect = { top: 0, left: 0, width: width, height: height }

  page.onConsoleMessage = function(msg) { console.log('console: ' + msg) }
  page.open(url, function() {
    console.log('Wait until loading complete...')
    waitUntil(isLoadingComplete, function() {
      delay(200, start)
    })
  })
}

if (args.length != 6) {
  console.log('Usage: phantomjs capture.js URL TMP_DIR TOTAL WIDTH HEIGHT')
  phantom.exit(1)
} else {
  const url = args[1]
  const tmpDir = args[2]
  const total = parseInt(args[3], 10)
  const width = parseInt(args[4], 10)
  const height = parseInt(args[5], 10)
  capture(url, tmpDir, total, width, height)
}


text:
namespace isl {

inline isl_pw_multi_aff *PwMultiAff::GetCopy() const {
  return isl_pw_multi_aff_copy((isl_pw_multi_aff *)This);
}
inline PwMultiAff &PwMultiAff::operator=(const PwMultiAff &Other) {
  isl_pw_multi_aff *New = Other.GetCopy();
  ctx = Other.Context();
  isl_pw_multi_aff_free((isl_pw_multi_aff *)This);
  This = New;
  return *this;
}
inline PwMultiAff PwMultiAff::fromMultiAff(const MultiAff &ma) {
  const Ctx &_ctx = ma.Context();
  _ctx.lock();
  isl_pw_multi_aff *That = isl_pw_multi_aff_from_multi_aff((ma).GetCopy());

  _ctx.unlock();
  if (_ctx.hasError()) {
    handleError("isl_pw_multi_aff_from_multi_aff returned a NULL pointer.");
  }

  return PwMultiAff(_ctx, That);
}

inline PwMultiAff PwMultiAff::fromPwAff(const PwAff &pa) {
  const Ctx &_ctx = pa.Context();
  _ctx.lock();
  isl_pw_multi_aff *That = isl_pw_multi_aff_from_pw_aff((pa).GetCopy());

  _ctx.unlock();
  if (_ctx.hasError()) {
    handleError("isl_pw_multi_aff_from_pw_aff returned a NULL pointer.");
  }

  return PwMultiAff(_ctx, That);
}

inline PwMultiAff PwMultiAff::alloc(const Set &set, const MultiAff &maff) {
  const Ctx &_ctx = maff.Context();
  _ctx.lock();
  isl_pw_multi_aff *That = isl_pw_multi_aff_alloc((set).GetCopy(), (maff).GetCopy());

  _ctx.unlock();
  if (_ctx.hasError()) {
    handleError("isl_pw_multi_aff_alloc returned a NULL pointer.");
  }

  return PwMultiAff(_ctx, That);
}

inline PwMultiAff PwMultiAff::readFromStr(const Ctx &ctx, std::string str) {
  const Ctx &_ctx = ctx.Context();
  _ctx.lock();
  isl_pw_multi_aff *That = isl_pw_multi_aff_read_from_str((ctx.Get()), str.c_str());

  _ctx.unlock();
  if (_ctx.hasError()) {
    handleError("isl_pw_multi_aff_read_from_str returned a NULL pointer.");
  }

  return PwMultiAff(_ctx, That);
}
inline PwMultiAff::~PwMultiAff() {
  isl_pw_multi_aff_free((isl_pw_multi_aff *)This);
  This = nullptr;
}
/// rief Release ownership of the wrapped object.
///
/// You are on your own now buddy.
/// The wrapper cannot be used anymore after calling Give()
///
///@return the wrapped isl object.
inline isl_pw_multi_aff *PwMultiAff::Give() {
  isl_pw_multi_aff *res = (isl_pw_multi_aff *)This;
  This = nullptr;
  return res;
}
/// \brief Unwrap the stored isl object.
/// \returns A the wrapped isl object.
inline isl_pw_multi_aff *PwMultiAff::Get() const {  return (isl_pw_multi_aff *)This;
}

inline PwMultiAff PwMultiAff::add(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_add((*this).GetCopy(), (pma2).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_add returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::alignParams(const Space &model) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_align_params((*this).GetCopy(), (model).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_align_params returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::coalesce() const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_coalesce((*this).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_coalesce returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline unsigned int PwMultiAff::dim(DimType type) const {
  ctx.lock();
  unsigned int res =  isl_pw_multi_aff_dim((*this).Get(), (enum isl_dim_type)type);
  ctx.unlock();
  return res;
}

inline Set PwMultiAff::domain() const {
  ctx.lock();
  isl_set * res =  isl_pw_multi_aff_domain((*this).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_domain returned a NULL pointer.");
  }
  return Set(ctx, res);
}

inline PwMultiAff PwMultiAff::dropDims(DimType type, unsigned int first, unsigned int n) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_drop_dims((*this).GetCopy(), (enum isl_dim_type)type, first, n);
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_drop_dims returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::flatRangeProduct(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_flat_range_product((*this).GetCopy(), (pma2).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_flat_range_product returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline Stat PwMultiAff::foreachPiece(const std::function<isl_stat(isl_set *, isl_multi_aff *, void *)> && fn, void * user) const {
  ctx.lock();
  isl_stat res =  isl_pw_multi_aff_foreach_piece((*this).Get(), get_fn_ptr<6>(fn), user);
  ctx.unlock();
  return (Stat)res;
}

inline Id PwMultiAff::getDimId(DimType type, unsigned int pos) const {
  ctx.lock();
  isl_id * res =  isl_pw_multi_aff_get_dim_id((*this).Get(), (enum isl_dim_type)type, pos);
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_get_dim_id returned a NULL pointer.");
  }
  return Id(ctx, res);
}

inline std::string PwMultiAff::getDimName(DimType type, unsigned int pos) const {
  ctx.lock();
  const char * res =  isl_pw_multi_aff_get_dim_name((*this).Get(), (enum isl_dim_type)type, pos);
  ctx.unlock();
  std::string res_;
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_get_dim_name returned a NULL pointer.");
  }
  res_ = res;
  return res_;
}

inline Space PwMultiAff::getDomainSpace() const {
  ctx.lock();
  isl_space * res =  isl_pw_multi_aff_get_domain_space((*this).Get());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_get_domain_space returned a NULL pointer.");
  }
  return Space(ctx, res);
}

inline PwAff PwMultiAff::getPwAff(int pos) const {
  ctx.lock();
  isl_pw_aff * res =  isl_pw_multi_aff_get_pw_aff((*this).Get(), pos);
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_get_pw_aff returned a NULL pointer.");
  }
  return PwAff(ctx, res);
}

inline Space PwMultiAff::getSpace() const {
  ctx.lock();
  isl_space * res =  isl_pw_multi_aff_get_space((*this).Get());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_get_space returned a NULL pointer.");
  }
  return Space(ctx, res);
}

inline Id PwMultiAff::getTupleId(DimType type) const {
  ctx.lock();
  isl_id * res =  isl_pw_multi_aff_get_tuple_id((*this).Get(), (enum isl_dim_type)type);
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_get_tuple_id returned a NULL pointer.");
  }
  return Id(ctx, res);
}

inline std::string PwMultiAff::getTupleName(DimType type) const {
  ctx.lock();
  const char * res =  isl_pw_multi_aff_get_tuple_name((*this).Get(), (enum isl_dim_type)type);
  ctx.unlock();
  std::string res_;
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_get_tuple_name returned a NULL pointer.");
  }
  res_ = res;
  return res_;
}

inline PwMultiAff PwMultiAff::gist(const Set &set) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_gist((*this).GetCopy(), (set).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_gist returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::gistParams(const Set &set) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_gist_params((*this).GetCopy(), (set).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_gist_params returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline Bool PwMultiAff::hasTupleId(DimType type) const {
  ctx.lock();
  isl_bool res =  isl_pw_multi_aff_has_tuple_id((*this).Get(), (enum isl_dim_type)type);
  ctx.unlock();
  return (Bool)res;
}

inline Bool PwMultiAff::hasTupleName(DimType type) const {
  ctx.lock();
  isl_bool res =  isl_pw_multi_aff_has_tuple_name((*this).Get(), (enum isl_dim_type)type);
  ctx.unlock();
  return (Bool)res;
}

inline PwMultiAff PwMultiAff::intersectDomain(const Set &set) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_intersect_domain((*this).GetCopy(), (set).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_intersect_domain returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::intersectParams(const Set &set) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_intersect_params((*this).GetCopy(), (set).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_intersect_params returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline Bool PwMultiAff::plainIsEqual(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_bool res =  isl_pw_multi_aff_plain_is_equal((*this).Get(), (pma2).Get());
  ctx.unlock();
  return (Bool)res;
}

inline PwMultiAff PwMultiAff::product(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_product((*this).GetCopy(), (pma2).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_product returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::projectDomainOnParams() const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_project_domain_on_params((*this).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_project_domain_on_params returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::pullbackMultiAff(const MultiAff &ma) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_pullback_multi_aff((*this).GetCopy(), (ma).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_pullback_multi_aff returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::pullbackPwMultiAff(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_pullback_pw_multi_aff((*this).GetCopy(), (pma2).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_pullback_pw_multi_aff returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::rangeProduct(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_range_product((*this).GetCopy(), (pma2).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_range_product returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::scaleVal(const Val &v) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_scale_val((*this).GetCopy(), (v).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_scale_val returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::setDimId(DimType type, unsigned int pos, const Id &id) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_set_dim_id((*this).GetCopy(), (enum isl_dim_type)type, pos, (id).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_set_dim_id returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::setPwAff(unsigned int pos, const PwAff &pa) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_set_pw_aff((*this).GetCopy(), pos, (pa).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_set_pw_aff returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::setTupleId(DimType type, const Id &id) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_set_tuple_id((*this).GetCopy(), (enum isl_dim_type)type, (id).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_set_tuple_id returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::sub(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_sub((*this).GetCopy(), (pma2).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_sub returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::unionAdd(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_union_add((*this).GetCopy(), (pma2).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_union_add returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::unionLexmax(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_union_lexmax((*this).GetCopy(), (pma2).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_union_lexmax returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

inline PwMultiAff PwMultiAff::unionLexmin(const PwMultiAff &pma2) const {
  ctx.lock();
  isl_pw_multi_aff * res =  isl_pw_multi_aff_union_lexmin((*this).GetCopy(), (pma2).GetCopy());
  ctx.unlock();
  if (ctx.hasError()) {
    handleError("isl_pw_multi_aff_union_lexmin returned a NULL pointer.");
  }
  return PwMultiAff(ctx, res);
}

} // namespace isl
#endif //ISL_CXX_PwMultiAff_IMPL_H


text:
%% Example 3 for utilizing the LDA model
% This example shows how to order topics according to co-usage in documents
% This will an ordering over topics where topics that co-appear often with
% other topics in documents to have similar indices.
%
% This examples uses the OrderTopics function. In this procedure, for each
% topic, the probability distribution over documents is calculated. For
% each topic pair (i,j), the (symmetrized) KL distance between topic
% distributions i and j is calculated. The KL distances are then subjected
% multidimensional scaling (MDS). The first dimension of the MDS solution
% is then used to get an ordering for topics.
%
% load a document-topic count matrix saved for the nips dataset
load 'ldasingle_nips';
load 'words_nips';

%%
% extract the topics in a cell array of strings
[S]=WriteTopics( WP,BETA,WO,5,0.6 );

%%
% order these topics using the OrderTopics function
[ Order ] = OrderTopics( DP,ALPHA );

%%
% and show the resulting ordering
S( Order )


text:
<?xml version="1.0" encoding="UTF-8"?>
<camelContext id="myCamel" errorHandlerRef="dlc" xmlns="http://camel.apache.org/schema/spring">
  <errorHandler id="dlc" type="DeadLetterChannel" deadLetterUri="log://deadLetterQueue">
    <redeliveryPolicy delayPattern="1:60000;2:300000;3:3600000;4:7200000;5:14400000;6:43200000"
                      retryAttemptedLogLevel="ERROR" asyncDelayedRedelivery="true" maximumRedeliveries="6"/>
  </errorHandler>
  <route>
    <from uri="file:src/data?noop=true"/>
    <choice>
      <when>
        <xpath>/person/city = 'London'</xpath>
        <log message="UK message"/>
        <to uri="file:target/messages/uk"/>
      </when>
      <otherwise>
        <log message="Other message"/>
        <to uri="file:target/messages/others"/>
      </otherwise>
    </choice>
  </route>
</camelContext>


text:
#include <limits.h>
#include "glxclient.h"
#include "glx_error.h"
#include <xcb/glx.h>
#include <X11/Xlib-xcb.h>

#include <assert.h>

#if INT_MAX != 2147483647
#error This code requires sizeof(uint32_t) == sizeof(int).
#endif

_X_HIDDEN GLXContext
glXCreateContextAttribsARB(Display *dpy, GLXFBConfig config,
			   GLXContext share_context, Bool direct,
			   const int *attrib_list)
{
   xcb_connection_t *const c = XGetXCBConnection(dpy);
   struct glx_config *const cfg = (struct glx_config *) config;
   struct glx_context *const share = (struct glx_context *) share_context;
   struct glx_context *gc = NULL;
   unsigned num_attribs = 0;
   struct glx_screen *psc;
   xcb_generic_error_t *err;
   xcb_void_cookie_t cookie;
   unsigned dummy_err = 0;

   if (dpy == NULL || cfg == NULL)
      return NULL;

   /* This means that either the caller passed the wrong display pointer or
    * one of the internal GLX data structures (probably the fbconfig) has an
    * error.  There is nothing sensible to do, so return an error.
    */
   psc = GetGLXScreenConfigs(dpy, cfg->screen);
   if (psc == NULL)
      return NULL;

   assert(cfg->screen == psc->scr);

   /* Count the number of attributes specified by the application.  All
    * attributes appear in pairs, except the terminating None.
    */
   if (attrib_list != NULL) {
      for (/* empty */; attrib_list[num_attribs * 2] != 0; num_attribs++)
	 /* empty */ ;
   }

   if (direct && psc->vtable->create_context_attribs) {
      /* GLX drops the error returned by the driver.  The expectation is that
       * an error will also be returned by the server.  The server's error
       * will be delivered to the application.
       */
      gc = psc->vtable->create_context_attribs(psc, cfg, share, num_attribs,
					       (const uint32_t *) attrib_list,
					       &dummy_err);
   }

   if (gc == NULL)
      gc = indirect_create_context(psc, cfg, share, 0);

   gc->xid = xcb_generate_id(c);
   gc->share_xid = (share != NULL) ? share->xid : 0;

   /* The manual pages for glXCreateContext and glXCreateNewContext say:
    *
    *     "NULL is returned if execution fails on the client side."
    *
    * If the server generates an error, the application is supposed to catch
    * the protocol error and handle it.  Part of handling the error is freeing
    * the possibly non-NULL value returned by this function.
    */
#ifdef HAVE_XCB_GLX_CREATE_CONTEXT
   cookie =
      xcb_glx_create_context_attribs_arb_checked(c,
						 gc->xid,
						 cfg->fbconfigID,
						 cfg->screen,
						 gc->share_xid,
						 gc->isDirect,
						 num_attribs,
						 (const uint32_t *)
						 attrib_list);
   err = xcb_request_check(c, cookie);
#else
   /* This is a hugely ugly hack to make things compile on systems that lack
    * the proper XCB version.
    */
   memset(&cookie, 0, sizeof(cookie));

   err = calloc(1, sizeof(*err));
   err->error_code = BadRequest;
   err->sequence = dpy->request;
   err->resource_id = gc->xid;
   err->minor_code = gc->majorOpcode;
   err->major_code = 34;
#endif
   if (err != NULL) {
      gc->vtable->destroy(gc);
      gc = NULL;

      __glXSendErrorForXcb(dpy, err);
      free(err);
   }

   return (GLXContext) gc;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
   Copyright (C) 2008 Romain Guy

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"

    android:orientation="vertical"
    android:background="@android:drawable/toast_frame">

    <TextView
        android:id="@+id/message"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="12dip"

        android:textAppearance="@android:style/TextAppearance.Small"
        android:textColor="@color/bright_foreground_dark"
        android:shadowColor="#bb000000"
        android:shadowRadius="2.75" />

    <ImageView
        android:id="@+id/cover"

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="6dip" />

</LinearLayout>


text:
% communicates with openrave
% orCommunicator uses the current setting in orConnectionParams
% to read the correct ip and port headers
% readline [optional] - if set, will read the output of the command.
%                       Some commands do not send an output, so the
%                       function can freeze indefinitely.
function [out, sockets] = orCommunicator(command_str, readline)
global orConnectionParams orOpenedSockets

out = [];
if( ~exist('readline','var') )
    readline = 0;
end

sockid = 0;
if( ~isempty(orConnectionParams) )
    index = 1;
    while(index <= length(orOpenedSockets))
        if( strcmp(orConnectionParams.ip, orOpenedSockets{index}.ip) & ...
            orConnectionParams.port == orOpenedSockets{index}.port )
            sockid = orOpenedSockets{index}.sockid;
            break;
        end
        index = index + 1;
    end

    if( sockid == 0 )
        % create a new socket
        [ip, port, sockid] = orcreate(orConnectionParams.ip, orConnectionParams.port);
    else
        [ip, port, sockid] = orcreate(sockid, orConnectionParams.ip, orConnectionParams.port);
        if( index > 0 )
            % believe that
            ip = orOpenedSockets{index}.ip;
            port = orOpenedSockets{index}.port;
        end
    end

    if( sockid == 0 )
        % delete
        if( index <= length(orOpenedSockets) )
            orOpenedSockets(index) = [];
        end
    else
        % succeeded
        sockparams.ip = ip;
        sockparams.port = port;
        sockparams.sockid = sockid;
        sockparams.default = 0;
        orOpenedSockets{index} = sockparams;
    end
else
    % create a default socket

    % first search
    index = 1;
    while(index <= length(orOpenedSockets) )
        if( orOpenedSockets{index}.default)
            sockid = orOpenedSockets{index}.sockid;
            break;
        end
    end

    if( sockid > 0 )
        [ip, port, sockid] = orcreate(sockid);
        orOpenedSockets{index}.sockid = sockid;
        if( sockid == 0 )
            orOpenedSockets(index) = [];
        end
    else
        [ip, port, sockid] = orcreate();

        if( sockid > 0 )
            sockparams.ip = ip;
            sockparams.port = port;
            sockparams.sockid = sockid;
            sockparams.default = 1;

            index = 1;
            found = 0;
            while(index <= length(orOpenedSockets))
                if( strcmp(ip, orOpenedSockets{index}.ip) & ...
                    port == orOpenedSockets{index}.port )
                    orOpenedSockets{index}.sockid = sockid;
                    found = 1;
                end
                index = index + 1;
            end

            if( found == 0 )
                % add
                orOpenedSockets{end+1} = sockparams;
            end
        end
    end
end

if( sockid == 0 )
    error('failed to init connection');
end

orwrite(command_str, sockid);

if( readline )
    out = orread(sockid);
end

sockets = orOpenedSockets;


text:
package com.minkov.demos.mvp.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;

import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.ExpandableDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.SectionDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.minkov.demos.mvp.Locations.LocationsActivity;
import com.minkov.demos.mvp.PersonsLists.PersonsListActivity;
import com.minkov.demos.mvp.Profile.ProfileActivity;

import dagger.android.support.DaggerAppCompatActivity;

/**
 * Base activity for providing drawer functionality
 */
public abstract class BaseDrawerActivity extends BaseActivity implements Drawer.OnDrawerItemClickListener {

    private static final String EXTRA_IDENTIFIER = "EXTRA_IDENTIFIER";
    private Drawer mDrawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupDrawer();
    }

    private void setupDrawer() {
        Intent intent = getIntent();
        long currentIdentifier = intent.getLongExtra(EXTRA_IDENTIFIER, 1);

        Toolbar toolbar = getToolbar();
        mDrawer = new DrawerBuilder()
                .withActivity(this)
                .withToolbar(toolbar)
                .addDrawerItems(new PrimaryDrawerItem()
                        .withIdentifier(1)
                        .withName("Persons List")
                )
                .addDrawerItems(new ExpandableDrawerItem()
                        .withName("APIs")
                        .withSubItems(
                                new SecondaryDrawerItem()
                                        .withIdentifier(3)
                                        .withName("Location")
                        ))
                .addStickyDrawerItems(
                        new PrimaryDrawerItem()
                                .withIdentifier(2)
                                .withName("Profile")
                )
                .withSelectedItem(currentIdentifier)
                .withOnDrawerItemClickListener(this)
                .build();

    }

    /**
     * Method for providing toolbar for drawer button
     *
     * @return the toolbar element of the view
     */
    protected abstract Toolbar getToolbar();

    @Override
    public boolean onItemClick(
            View view,
            int position,
            IDrawerItem drawerItem) {

        Intent intent = null;
        switch ((int) drawerItem.getIdentifier()) {
            case 1:
                intent = new Intent(this, PersonsListActivity.class);
                break;
            case 2:
                intent = new Intent(this, ProfileActivity.class);
                break;
            case 3:
                intent = new Intent(this, LocationsActivity.class);
                break;
            default:
                return false;
        }

        intent.putExtra(EXTRA_IDENTIFIER, drawerItem.getIdentifier());

        startActivity(intent);
        return true;
    }

    public Drawer getDrawer() {
        return mDrawer;
    }
}


text:
import { htmlEllipsis } from './html-ellipsis';
export { htmlEllipsis };
export default htmlEllipsis;


text:
require File.dirname(__FILE__) + '/../../spec_helper'
require 'set'
require File.dirname(__FILE__) + '/shared/add'

describe "Set#<<" do
  it_behaves_like :set_add, Set, :<<
end


text:
with open("Brown-Retagged.txt") as fp:
    for line in fp:
        line = line.strip().split()
        for tuple in line:
            word, _, pos = tuple.partition('_')
            print '{}\t{}'.format(word, pos)
        print ''


text:
import PropTypes from 'prop-types';
import React from "react";
import { Link } from "react-server";

const headerColumns = [
	{ id: 0, name: "Name", link: "/" },
	{ id: 1, name: "Mass", "link": "/sort/mass" },
	{ id: 2, name: "Year", "link": "/sort/year" },
];
const Header = ({ onHeaderClick }) => (

			{headerColumns.map(h =>
				 onHeaderClick(h.id)}>
					<Link path={h.link}>{h.name}</Link>

			)}

);

const Row = ({ id, name, mass, year, selected, onRowClick }) => {
	const selectedClass = selected ? "info pointer" : "pointer";
	return (

 onRowClick(id)} className={selectedClass}>
			{name}	{mass}	{year}

	);
};

const Table = ({ header, meteors, onRowClick, onHeaderClick }) => (

			{meteors.map(meteor =>
				<Row
					key={meteor.id}
					onRowClick={onRowClick}
					{...meteor}
				/>
			)}

);

Table.propTypes = {
	meteors: PropTypes.arrayOf(PropTypes.shape({
		id: PropTypes.string.isRequired,
		name: PropTypes.string.isRequired,
		mass: PropTypes.string.isRequired,
		year: PropTypes.string.isRequired,
		selected: PropTypes.bool,
	}).isRequired).isRequired,
	onHeaderClick: PropTypes.func.isRequired,
	onRowClick: PropTypes.func.isRequired,
}

export default Table;


text:
Vue Calculator
==========================

Sandbox project to get familiar with Vue


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

namespace Mozu.Api.Urls.Commerce.Customer.Accounts
{
	public partial class CustomerContactUrl
	{

		/// <summary>
        /// Get Resource Url for GetAccountContact
        /// </summary>
        /// <param name="accountId">Unique identifier of the customer account.</param>
        /// <param name="contactId">Unique identifer of the customer account contact being updated.</param>
        /// <param name="responseFields">Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.</param>
        /// <param name="userId">Unique identifier of the user whose tenant scopes you want to retrieve.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl GetAccountContactUrl(int accountId, int contactId, string userId =  null, string responseFields =  null)
		{
			var url = "/api/commerce/customer/accounts/{accountId}/contacts/{contactId}?userId={userId}&responseFields={responseFields}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "accountId", accountId);
			mozuUrl.FormatUrl( "contactId", contactId);
			mozuUrl.FormatUrl( "responseFields", responseFields);
			mozuUrl.FormatUrl( "userId", userId);
			return mozuUrl;
		}

		/// <summary>
        /// Get Resource Url for GetAccountContacts
        /// </summary>
        /// <param name="accountId">Unique identifier of the customer account.</param>
        /// <param name="filter">A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters.</param>
        /// <param name="pageSize">When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50.</param>
        /// <param name="responseFields">Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.</param>
        /// <param name="sortBy">The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information.</param>
        /// <param name="startIndex">When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50.</param>
        /// <param name="userId">Unique identifier of the user whose tenant scopes you want to retrieve.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl GetAccountContactsUrl(int accountId, int? startIndex =  null, int? pageSize =  null, string sortBy =  null, string filter =  null, string userId =  null, string responseFields =  null)
		{
			var url = "/api/commerce/customer/accounts/{accountId}/contacts?startIndex={startIndex}&pageSize={pageSize}&sortBy={sortBy}&filter={filter}&userId={userId}&responseFields={responseFields}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "accountId", accountId);
			mozuUrl.FormatUrl( "filter", filter);
			mozuUrl.FormatUrl( "pageSize", pageSize);
			mozuUrl.FormatUrl( "responseFields", responseFields);
			mozuUrl.FormatUrl( "sortBy", sortBy);
			mozuUrl.FormatUrl( "startIndex", startIndex);
			mozuUrl.FormatUrl( "userId", userId);
			return mozuUrl;
		}

				/// <summary>
        /// Get Resource Url for AddAccountContact
        /// </summary>
        /// <param name="accountId">Unique identifier of the customer account.</param>
        /// <param name="responseFields">Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl AddAccountContactUrl(int accountId, string responseFields =  null)
		{
			var url = "/api/commerce/customer/accounts/{accountId}/contacts?responseFields={responseFields}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "accountId", accountId);
			mozuUrl.FormatUrl( "responseFields", responseFields);
			return mozuUrl;
		}

				/// <summary>
        /// Get Resource Url for UpdateAccountContact
        /// </summary>
        /// <param name="accountId">Unique identifier of the customer account.</param>
        /// <param name="contactId">Unique identifer of the customer account contact being updated.</param>
        /// <param name="responseFields">Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.</param>
        /// <param name="userId">Unique identifier of the user whose tenant scopes you want to retrieve.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl UpdateAccountContactUrl(int accountId, int contactId, string userId =  null, string responseFields =  null)
		{
			var url = "/api/commerce/customer/accounts/{accountId}/contacts/{contactId}?userId={userId}&responseFields={responseFields}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "accountId", accountId);
			mozuUrl.FormatUrl( "contactId", contactId);
			mozuUrl.FormatUrl( "responseFields", responseFields);
			mozuUrl.FormatUrl( "userId", userId);
			return mozuUrl;
		}

		/// <summary>
        /// Get Resource Url for AddAccountContactList
        /// </summary>
        /// <param name="accountId">Unique identifier of the customer account.</param>
        /// <param name="responseFields">Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl AddAccountContactListUrl(int accountId, string responseFields =  null)
		{
			var url = "/api/commerce/customer/accounts/{accountId}/contacts?responseFields={responseFields}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "accountId", accountId);
			mozuUrl.FormatUrl( "responseFields", responseFields);
			return mozuUrl;
		}

				/// <summary>
        /// Get Resource Url for DeleteAccountContact
        /// </summary>
        /// <param name="accountId">Unique identifier of the customer account.</param>
        /// <param name="contactId">Unique identifer of the customer account contact being updated.</param>
        /// <returns>
        /// String - Resource Url
        /// </returns>
        public static MozuUrl DeleteAccountContactUrl(int accountId, int contactId)
		{
			var url = "/api/commerce/customer/accounts/{accountId}/contacts/{contactId}";
			var mozuUrl = new MozuUrl(url, MozuUrl.UrlLocation.TENANT_POD, false) ;
			mozuUrl.FormatUrl( "accountId", accountId);
			mozuUrl.FormatUrl( "contactId", contactId);
			return mozuUrl;
		}

	}
}


text:
	#error "include 'stdafx.h' before including this file for PCH"
#endif

#include "resource.h"		// main symbols

// CiservercontrollerApp:
// See iservercontroller.cpp for the implementation of this class
//
namespace IServerController
{
	class CiservercontrollerApp : public CWinApp
	{
	public:
		CiservercontrollerApp();

		// Overrides
	public:
		virtual BOOL InitInstance();

		// Implementation

		DECLARE_MESSAGE_MAP()
	};
}

extern IServerController::CiservercontrollerApp theApp;


text:
package org.openbox.dashboard;

import org.moonlightcontroller.managers.models.IRequestSender;
import org.moonlightcontroller.managers.models.messages.Error;
import org.moonlightcontroller.managers.models.messages.IMessage;
import org.moonlightcontroller.managers.models.messages.ReadResponse;

import java.util.logging.Logger;

public class DashboardRequestSender implements IRequestSender {
    private final static Logger LOG = Logger.getLogger(DashboardRequestSender.class.getName());

    @Override
    public void onSuccess(IMessage message) {
        if (message instanceof ReadResponse){
            ReadResponse rr = (ReadResponse)message;

            LOG.info("got a read response:" + rr.getBlockId() + "::" + rr.getReadHandle() + "::" + rr.getResult());
        }
    }

    @Override
    public void onFailure(Error err) {
        LOG.info("got an error:" + err.getError_type() + "::" + err.getExtended_message());
    }
}


text:
package edu.duke.cabig.c3pr.web.security;

import edu.duke.cabig.c3pr.constants.UserPrivilegeType;
import edu.duke.cabig.c3pr.domain.Study;
import edu.duke.cabig.c3pr.domain.StudyOrganization;
import edu.duke.cabig.c3pr.domain.StudySite;
import edu.duke.cabig.c3pr.utils.StringUtils;
import gov.nih.nci.cabig.ctms.acegi.csm.authorization.CSMAuthorizationCheck;
import gov.nih.nci.cabig.ctms.web.tabs.Tab;

import java.util.Map;

import org.acegisecurity.Authentication;
import org.springframework.beans.factory.annotation.Required;

public class StudyOrganizationTabAuthorizationCheck implements TabAuthroizationCheck{

	private Map<String, String> tabBasedPrivilegeMap;

	private Map<String, String> tabBasedScopeMap;

	private CSMAuthorizationCheck csmAuthorizationCheck;

	public boolean checkAuthorization(Authentication authentication, String privilege , Tab tab,
			Object domainObject, String scope) {
		if(StringUtils.getBlankIfNull(privilege).equals("")){
			privilege = UserPrivilegeType.getByCode(tabBasedPrivilegeMap.get(getKeyValue(tab))).name();
		}
		if(StringUtils.getBlankIfNull(scope).equals("")){
			scope = tabBasedScopeMap.get(getKeyValue(tab));
		}
		if(StringUtils.getBlankIfNull(scope).equals("")){
			throw new RuntimeException("Invalid scope.");
		}
		Study study = (Study) domainObject;
		if(scope.equals(COCENTER_SCOPED_AUTHRORIZATION_CHECK)){
			return csmAuthorizationCheck.checkAuthorization(authentication, privilege, study.getStudyCoordinatingCenter().getHealthcareSite());
		}else if(scope.equals(STUDYSITE_SCOPED_AUTHRORIZATION_CHECK)){
			if(csmAuthorizationCheck.checkAuthorization(authentication, privilege, study.getStudyCoordinatingCenter().getHealthcareSite())){
				return true;
			}
			for(StudySite studySite : study.getStudySites()){
				if(csmAuthorizationCheck.checkAuthorization(authentication, privilege, studySite.getHealthcareSite())){
					return true;
				}
			}
			return false;
		}else if(scope.equals(STUDYORGANIZATION_SCOPED_AUTHRORIZATION_CHECK)){
			for(StudyOrganization studyOrganization : study.getStudyOrganizations()){
				if(csmAuthorizationCheck.checkAuthorization(authentication, privilege, studyOrganization.getHealthcareSite())){
					return true;
				}
			}
			return false;
		}else{
			throw new RuntimeException("Invalid scope.");
		}
	}

	protected String getKeyValue(Tab tab) {
        return tab.getClass().getName();
    }

	public void setTabBasedScopeMap(Map<String, String> tabBasedScopeMap) {
		this.tabBasedScopeMap = tabBasedScopeMap;
	}

	@Required
	public void setCsmAuthorizationCheck(CSMAuthorizationCheck csmAuthorizationCheck) {
		this.csmAuthorizationCheck = csmAuthorizationCheck;
	}

	@Required
	public void setTabBasedPrivilegeMap(Map<String, String> tabBasedPrivilegeMap) {
		this.tabBasedPrivilegeMap = tabBasedPrivilegeMap;
	}
}


text:
package com.graphhopper.reader;

import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

/**
 * @author Peter Karich
 */
public class OSMNodeTest {
    @Test
    public void testSetTags() {
        ReaderNode instance = new ReaderNode(0, 10, 10);
        assertTrue(Double.isNaN(instance.getEle()));

        instance.setTag("ele", "-10.1");
        assertEquals(-10.1, instance.getEle(), 1e-1);

        // oh OSM
        instance.setTag("ele", "-10,1");
        assertEquals(-10.1, instance.getEle(), 1e-1);
        // do not parse other stuff
        instance.setTag("ele", "-9.1 m.");
        assertEquals(-10.1, instance.getEle(), 1e-1);

        // empty values
        instance.setTag("ele", "");
        assertTrue(Double.isNaN(instance.getEle()));
        instance.setTag("ele", "-10.1");
        assertEquals(-10.1, instance.getEle(), 1e-1);
        instance.setTag("ele", null);
        assertTrue(Double.isNaN(instance.getEle()));
    }
}


text:
package tenant

import (
	"context"
	"path"

	"github.com/influxdata/influxdb/v2"
	"github.com/influxdata/influxdb/v2/pkg/httpc"
)

// OnboardClientService connects to Influx via HTTP to perform onboarding operations
type OnboardClientService struct {
	Client *httpc.Client
}

// IsOnboarding determine if onboarding request is allowed.
func (s *OnboardClientService) IsOnboarding(ctx context.Context) (bool, error) {
	var resp isOnboardingResponse
	err := s.Client.
		Get(prefixOnboard).
		DecodeJSON(&resp).
		Do(ctx)

	if err != nil {
		return false, err
	}
	return resp.Allowed, nil
}

// OnboardInitialUser OnboardingResults.
func (s *OnboardClientService) OnboardInitialUser(ctx context.Context, or *influxdb.OnboardingRequest) (*influxdb.OnboardingResults, error) {
	res := &onboardingResponse{}

	err := s.Client.
		PostJSON(or, prefixOnboard).
		DecodeJSON(res).
		Do(ctx)

	if err != nil {
		return nil, err
	}

	bkt, err := res.Bucket.toInfluxDB()
	if err != nil {
		return nil, err
	}

	return &influxdb.OnboardingResults{
		Org:    &res.Organization.Organization,
		User:   &res.User.User,
		Auth:   res.Auth.toPlatform(),
		Bucket: bkt,
	}, nil
}

func (s *OnboardClientService) OnboardUser(ctx context.Context, or *influxdb.OnboardingRequest) (*influxdb.OnboardingResults, error) {
	res := &onboardingResponse{}

	err := s.Client.
		PostJSON(or, path.Join(prefixOnboard, "user")).
		DecodeJSON(res).
		Do(ctx)

	if err != nil {
		return nil, err
	}

	bkt, err := res.Bucket.toInfluxDB()
	if err != nil {
		return nil, err
	}

	return &influxdb.OnboardingResults{
		Org:    &res.Organization.Organization,
		User:   &res.User.User,
		Auth:   res.Auth.toPlatform(),
		Bucket: bkt,
	}, nil
}


text:
package com.sxjs.jd.composition.main;

import java.util.Map;

/**
 * Created by admin on 2017/3/12.
 */

public interface MainContract {
 interface View {
    void setText(String text);

    void showProgressDialogView();

    void hiddenProgressDialogView();
}

 interface Presenter {

    void destory();

    void saveData();

    Map getData();
}

}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/deploy/v1/cloud_deploy.proto

package com.google.cloud.deploy.v1;

public interface RetryJobRequestOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.deploy.v1.RetryJobRequest)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Required. Name of the Rollout. Format is
   * projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/
   * releases/{release}/rollouts/{rollout}.
   *

   *
   *
   * string rollout = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The rollout.
   */
  java.lang.String getRollout();
  /**
   *
   *
   *

   * Required. Name of the Rollout. Format is
   * projects/{project}/locations/{location}/deliveryPipelines/{deliveryPipeline}/
   * releases/{release}/rollouts/{rollout}.
   *

   *
   *
   * string rollout = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
   *
   *
   * @return The bytes for rollout.
   */
  com.google.protobuf.ByteString getRolloutBytes();

  /**
   *
   *
   *

   * Required. The phase ID the Job to retry belongs to.
   *

   *
   * string phase_id = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The phaseId.
   */
  java.lang.String getPhaseId();
  /**
   *
   *
   *

   * Required. The phase ID the Job to retry belongs to.
   *

   *
   * string phase_id = 2 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The bytes for phaseId.
   */
  com.google.protobuf.ByteString getPhaseIdBytes();

  /**
   *
   *
   *

   * Required. The job ID for the Job to retry.
   *

   *
   * string job_id = 3 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The jobId.
   */
  java.lang.String getJobId();
  /**
   *
   *
   *

   * Required. The job ID for the Job to retry.
   *

   *
   * string job_id = 3 [(.google.api.field_behavior) = REQUIRED];
   *
   * @return The bytes for jobId.
   */
  com.google.protobuf.ByteString getJobIdBytes();
}