text:
> A generic JSON-schema-based model editor, provided as an AngularJS directive for LaxarJS widgets.

This directive can be used to create JSON documents that are based on a certain schema.
The schema is translated into corresponding HTML elements and each item of the JSON structure bound to it accordingly.

## Installation

To retrieve a copy of this control you can either clone it directly using git or alternatively install it via Bower.
For general information on installing, styling and optimizing controls, have a look at the [LaxarJS documentation](https://github.com/LaxarJS/laxar/blob/master/docs/manuals/installing_controls.md).

### Setup Using Bower

Install the control:

```sh
bower install laxar-json-form-control
```

Reference the control from the `widget.json` of your widget:

```json
   "controls": [ "laxar-json-form-control" ]
```

## Usage

### Input/Output

The document is attached via a regular AngularJS ngModelController as a JSON string.
Parsing and stringification are handled within the directive itself.
The schema based on which the form is generated and validated is bound using the `ax-schema` attribute on the directive.
It needs to be a valid [JSON schema V3](http://tools.ietf.org/html/draft-zyp-json-schema-03) object.
Optionally one can provide form rendering instructions using the `ax-json-form` directive itself.
They are interpreted as a map from JSON paths to configuration options.
A path must map to a corresponding definition within the directive's schema.

Valid configuration properties for the time being are:

* `sortIndex:` an integer providing the order of object properties.
  A property with smaller index is listed before one of the same object with a larger index.
  Default sortIndex is 0.
  Only applies to object types.

* `type:` configures the type of an input field.
  Currently only `"textarea"` to support multiline input for strings is supported.

If entries of an array are to be configured, the `*` can be used as wildcard path fragment.
A configuration of pattern properties isn't possible for the time being.

Example:
```javascript
   {
      // should be sorted with sorting priority 4
      "someKey": { "sortIndex": 4 },
      // The description field of each entry in someArray should be rendered as textarea
      "someArray.*.description": { "type": "textarea" }
   }
```

### Validation

Validation is triggered automatically each time a value is changed.
In order to allow validation instantly or generally on demand one can `$broadcast` the `axJsonFormValidate` event.

To access the validation result one can listen to the `axJsonFormValidationResult` event.
It is triggered for each input directive that can validate, and it holds a unique ID of the directive and a possibly empty list of validation error messages.
A simpler way to simply know whether the form is valid or not is to bind a local scope property to the `ax-valid` attribute on the form directive.
As AngularJS events are handled synchronously, the binding should reflect the validity state of the form just after `axJsonFormValidate` was triggered.


text:
package com.jmcdale.remotelogcat.Adapters;

import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jmcdale.remotelogcat.Models.LogCatLine;
import com.jmcdale.remotelogcat.R;
import com.jmcdale.remotelogcat.Utils.AppUtils;

import java.util.LinkedList;

public class LogCatAdapter extends RecyclerView.Adapter<LogCatAdapter.ViewHolder> {

    private static final int MAX_LINES = 500;

    private LinkedList<LogCatLine> logCatLines = new LinkedList<>();

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.li_logcat_line, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(ViewHolder viewHolder, int position) {
        viewHolder.tvLogLevel.setText(logCatLines.get(position).getLogLevel());
        viewHolder.tvTag.setText(logCatLines.get(position).getTag());
        viewHolder.tvPid.setText("(" + String.valueOf(logCatLines.get(position).getPid()) + ")");
        viewHolder.tvLog.setText(logCatLines.get(position).getLog());

        int logLevelBgColor = Color.WHITE;
        int logLevelFgColor = Color.BLACK;
        switch (logCatLines.get(position).getLogLevel()){
            case "I":
                logLevelBgColor = Color.BLUE;
                logLevelFgColor = Color.WHITE;
                break;
            case "W":
                logLevelBgColor = Color.YELLOW;
                logLevelFgColor = Color.BLACK;
                break;
            case "D":
                logLevelBgColor = Color.DKGRAY;
                logLevelFgColor = Color.WHITE;
                break;
            case "E":
                logLevelBgColor = Color.RED;
                logLevelFgColor = Color.WHITE;
                break;
            case "V":
                break;
//            default:

        }
        viewHolder.tvLogLevel.setBackgroundColor(logLevelBgColor);
        viewHolder.tvLogLevel.setTextColor(logLevelFgColor);

        viewHolder.tvTag.setTextColor(AppUtils.getColorForTag(logCatLines.get(position).getTag()));
    }

    @Override
    public int getItemCount() {
        return logCatLines.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView tvLogLevel;
        TextView tvTag;
        TextView tvPid;
        TextView tvLog;

        public ViewHolder(View itemView) {
            super(itemView);

            tvLogLevel = (TextView) itemView.findViewById(R.id.tvLogLevel);
            tvTag = (TextView) itemView.findViewById(R.id.tvTag);
            tvPid = (TextView) itemView.findViewById(R.id.tvPid);
            tvLog = (TextView) itemView.findViewById(R.id.tvLog);
        }
    }

    //addToTop
//    public void addLine(String line) {
//        l++;
//        line = l + " " + line;
//        if (logCatLines.size() > MAX_LINES) {
//            logCatLines.removeLast();
//            notifyItemRemoved(logCatLines.size());
//        }
//        logCatLines.push(line);
//        notifyItemInserted(0);
//    }

    //addToBottom
    public void addLine(LogCatLine line) {
        if (logCatLines.size() > MAX_LINES) {
            logCatLines.pop();
            notifyItemRemoved(0);
        }
        logCatLines.offer(line);
        notifyItemInserted(logCatLines.size() - 1);
    }

    //addToBottom
//    public void addLine(String line) {
//        if (logCatLines.size() > MAX_LINES) {
//            logCatLines.pop();
//            notifyItemRemoved(0);
//        }
//        logCatLines.offer(line);
//        notifyItemInserted(logCatLines.size() - 1);
//    }

}

redpajama_set_name: RedPajamaGithub


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.
-->

<resources>
    <declare-styleable name="ShelvesView">
        <attr name="shelfBackground" format="reference" />
    </declare-styleable>

    <declare-styleable name="BookStore">
        <attr name="name" format="string" />
        <attr name="label" format="string" />
        <attr name="storeClass" format="string" />
    </declare-styleable>
</resources>


text:
# Description:
# Mark in color all glyph having Overlaps

# Credits:
# By James Puckett and Jens Kutilek
# http://typophile.com/node/84799

f = Font(fl.font)

# Unmark glyphs first
for glyphIndex in range(len(f.glyphs)):
	fl.font[glyphIndex].mark = 0

# make a copy of the current font
for glyphIndex in range(len(f.glyphs)):
	g = f[glyphIndex]
	if (len(g.components) > 1) or (len(g) > 0 and len(g.components) > 0):
		# only decompose composites made up of more than one component
		g.Decompose()
	if len(g) > 0:
		# glyph has outlines
		g2 = Glyph(g)
		g2.RemoveOverlap()
		if len(g) != len(g2):
			# different number of nodes
			fl.font[glyphIndex].mark = 10
		else:
			# check nodes
			for nodeIndex in range(len(g.nodes)):
				n = g.nodes[nodeIndex]
				n2 = g2.nodes[nodeIndex]
				if len(n) != len(n2):
					# nodes don't have the same number of points
					fl.font[glyphIndex].mark = 20
					break
				else:
					# check points
					for pointIndex in range(len(n.points)):
						if n[pointIndex].x != n2[pointIndex].x or n[pointIndex].y != n2[pointIndex].y:
							fl.font[glyphIndex].mark = 30
							break
fl.UpdateFont()

print "Done!"


text:
<?php

namespace Google\Service\Dataflow;

class AutoscalingEvent extends \Google\Model
{
  /**
   * @var string
   */
  public $currentNumWorkers;
  protected $descriptionType = StructuredMessage::class;
  protected $descriptionDataType = '';
  /**
   * @var string
   */
  public $eventType;
  /**
   * @var string
   */
  public $targetNumWorkers;
  /**
   * @var string
   */
  public $time;
  /**
   * @var string
   */
  public $workerPool;

  /**
   * @param string
   */
  public function setCurrentNumWorkers($currentNumWorkers)
  {
    $this->currentNumWorkers = $currentNumWorkers;
  }
  /**
   * @return string
   */
  public function getCurrentNumWorkers()
  {
    return $this->currentNumWorkers;
  }
  /**
   * @param StructuredMessage
   */
  public function setDescription(StructuredMessage $description)
  {
    $this->description = $description;
  }
  /**
   * @return StructuredMessage
   */
  public function getDescription()
  {
    return $this->description;
  }
  /**
   * @param string
   */
  public function setEventType($eventType)
  {
    $this->eventType = $eventType;
  }
  /**
   * @return string
   */
  public function getEventType()
  {
    return $this->eventType;
  }
  /**
   * @param string
   */
  public function setTargetNumWorkers($targetNumWorkers)
  {
    $this->targetNumWorkers = $targetNumWorkers;
  }
  /**
   * @return string
   */
  public function getTargetNumWorkers()
  {
    return $this->targetNumWorkers;
  }
  /**
   * @param string
   */
  public function setTime($time)
  {
    $this->time = $time;
  }
  /**
   * @return string
   */
  public function getTime()
  {
    return $this->time;
  }
  /**
   * @param string
   */
  public function setWorkerPool($workerPool)
  {
    $this->workerPool = $workerPool;
  }
  /**
   * @return string
   */
  public function getWorkerPool()
  {
    return $this->workerPool;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(AutoscalingEvent::class, 'Google_Service_Dataflow_AutoscalingEvent');


text:
package grequests

import "io"

const (
	localUserAgent = "GRequests 0.1"
)

// XMLCharDecoder is a helper type that takes a stream of bytes (not encoded in
// UTF-8) and returns a reader that encodes the bytes into UTF-8. This is done
// because Go's XML library only supports XML encoded in UTF-8
type XMLCharDecoder func(charset string, input io.Reader) (io.Reader, error)


text:
'use strict';

import CodeEditor from '../components/CodeEditor';
import React from 'react';
import ReactDOM from 'react-dom';

// TODO This is a huge hack.
// Remark transform this template to split code examples and their targets apart.
const mountCodeExample = (containerId, code) => {
  const container = document.getElementById(containerId);
  const parent = container.parentElement;

  const children = Array.prototype.filter.call(
    parent.children,
    child => child !== container,
  );
  children.forEach(child => parent.removeChild(child));

  const description = children
    .map(child => child.outerHTML)
    .join('')
    .replace(/`([^`]+)`/g, '$1');

  ReactDOM.render(
    <CodeEditor code={code}>
      {
}
    </CodeEditor>,
    container,
  );
};

export default mountCodeExample;


text:
__author__ = 'fhaynes'

from os.path import abspath, dirname
import sys

project_dir = abspath(dirname(dirname(__file__)))
sys.path.insert(0, project_dir)
from django.core.urlresolvers import resolve
from django.test import TestCase
from django.test.client import Client
from website.views import reservationViews
from website.models import *
from datetime import datetime, timedelta
from django.test.client import RequestFactory
from django.utils import timezone
import pytz

class SchedulingTests(TestCase):

    def setUp(self):
        self.factory = RequestFactory()
        generic_user = User.objects.create(pk=1, username='Test User 1')
        delivery_action_type = ActionType.objects.create(pk=1, ActionTypeName="Delivery")
        pickup_action_type = ActionType.objects.create(pk=2, ActionTypeName="Return")
        storage_location = Location.objects.create(pk=1,
                                                   BuildingID=Building.objects.create(pk=1, BuildingCode='SML', BuildingName='Smullin'),
                                                   RoomNumber="122",
                                                   LocationDescription="Smullin 122 Closet")
        delivery_location = Location.objects.create(pk=2,
                                                    BuildingID=Building.objects.create(pk=2, BuildingCode='FORD', BuildingName = 'Ford'),
                                                    RoomNumber="202",
                                                    LocationDescription="Ford Lab")

        first_reservation = Reservation.objects.create(pk=1,
                                                       CustomerID=generic_user,
                                                       OwnerID=generic_user,
                                                       CustomerPhone="",
                                                       CustomerEmail="",
                                                       CustomerDept="",
                                                       CustomerStatus="",
                                                       ReservationNotes="",
                                                       EventTitle="")

        start = timezone.now() + timedelta(days=1)
        end = timezone.now() + timedelta(days=1, hours=1)

        first_action = Action.objects.create(ActionID=1,
                                             AssignedOperatorID=generic_user,
                                             ActionTypeID=delivery_action_type,
                                             StartTime=start,
                                             EndTime=end,
                                             Origin=storage_location,
                                             Destination=delivery_location,
                                             ActionStatus="Incomplete",
                                             ActionNotes="This is action 1")
        first_action.Reservation.add(first_reservation)

        start = timezone.now() + timedelta(days=2)
        end = timezone.now() + timedelta(days=2, hours = 1)
        second_action = Action.objects.create(ActionID=2,
                                              AssignedOperatorID=generic_user,
                                              ActionTypeID=pickup_action_type,
                                              StartTime=start,
                                              EndTime=end,
                                              Origin=delivery_location,
                                              Destination=storage_location,
                                              ActionStatus="Incomplete",
                                              ActionNotes="This is action 2")
        second_action.Reservation.add(first_reservation)

        generic_category = Label.objects.create(LabelID=1,
                                                LabelName="Label",
                                                ParentCategory=None)

        generic_collection = Collection.objects.create(CollectionID=1,
                                                       CollectionName="Collection 1",
                                                       CollectionDescription="")

        generic_item_brand = ItemBrand.objects.create(BrandID=1,
                                                      BrandName="Unit test brand")

        generic_model = ItemModel.objects.create(ModelID=1,
                                                 ModelDesignation="Unit test model")

        generic_status = Status.objects.create(StatusID=1,
                                               StatusDescription="Unit test")

        i1 = InventoryItem.objects.create(ItemID=1,
                                     Description="Item 1",
                                     CategoryID=generic_category,
                                     StorageLocation=storage_location,
                                     CollectionID=generic_collection,
                                     Notes="Created by unit test",
                                     AlternateID=None,
                                     BrandID=generic_item_brand,
                                     ModelID=generic_model,
                                     ParentItem=None,
                                     StatusID=generic_status)

        i2 = InventoryItem.objects.create(ItemID=2,
                                     Description="Item 2",
                                     CategoryID=generic_category,
                                     StorageLocation=storage_location,
                                     CollectionID=generic_collection,
                                     Notes="Created by unit test",
                                     AlternateID=None,
                                     BrandID=generic_item_brand,
                                     ModelID=generic_model,
                                     ParentItem=None,
                                     StatusID=generic_status)

        i1.Action.add(first_action, second_action)
        i2.Action.add(first_action, second_action)

    def test_b_starts_after_a_ends(self):
        res = Reservation.objects.create(pk=2,
                                         CustomerID=User.objects.get(pk=1),
                                         OwnerID=User.objects.get(pk=1),
                                         CustomerPhone="",
                                         CustomerEmail="",
                                         CustomerDept="",
                                         CustomerStatus="",
                                         ReservationNotes="",
                                         EventTitle="Second Test Reservation")

        start = timezone.now() + timedelta(days=3)
        end = timezone.now() + timedelta(days=3, hours=1)
        a1 = Action.objects.create(ActionID=3,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=1),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=1),
                                   Destination=Location.objects.get(pk=2),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a1.Reservation.add(res)

        start = timezone.now() + timedelta(days=4)
        end = timezone.now() + timedelta(days=4, hours=1)
        a2 = Action.objects.create(ActionID=4,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=2),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=2),
                                   Destination=Location.objects.get(pk=1),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a2.Reservation.add(res)

        request = self.factory.get('/findAvailableEquipment/?actions[]=3,4&categoryid=1')
        response = reservationViews.findAvailableEquipment(request)
        self.assertEqual(response.status_code, 200)

    def test_b_starts_during_a(self):
        res = Reservation.objects.create(pk=2,
                                         CustomerID=User.objects.get(pk=1),
                                         OwnerID=User.objects.get(pk=1),
                                         CustomerPhone="",
                                         CustomerEmail="",
                                         CustomerDept="",
                                         CustomerStatus="",
                                         ReservationNotes="",
                                         EventTitle="Second Test Reservation")

        start = timezone.now() + timedelta(days=1, hours=6)
        end = timezone.now() + timedelta(days=1, hours=7)
        a1 = Action.objects.create(ActionID=5,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=1),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=1),
                                   Destination=Location.objects.get(pk=2),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a1.Reservation.add(res)

        start = timezone.now() + timedelta(days=4)
        end = timezone.now() + timedelta(days=4, hours=1)
        a2 = Action.objects.create(ActionID=6,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=2),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=2),
                                   Destination=Location.objects.get(pk=1),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a2.Reservation.add(res)

        request = self.factory.get('/findAvailableEquipment/?actions[]=5,6&categoryid=1')
        response = reservationViews.findAvailableEquipment(request)
        self.assertEqual(response.status_code, 501)

    def test_b_starts_after_a1_ends_before_a2(self):
        res = Reservation.objects.create(pk=2,
                                         CustomerID=User.objects.get(pk=1),
                                         OwnerID=User.objects.get(pk=1),
                                         CustomerPhone="",
                                         CustomerEmail="",
                                         CustomerDept="",
                                         CustomerStatus="",
                                         ReservationNotes="",
                                         EventTitle="Second Test Reservation")

        start = timezone.now() + timedelta(days=1, hours=2)
        end = timezone.now() + timedelta(days=1, hours=3)
        a1 = Action.objects.create(ActionID=3,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=1),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=1),
                                   Destination=Location.objects.get(pk=2),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a1.Reservation.add(res)

        start = timezone.now() + timedelta(days=1, hours=6)
        end = timezone.now() + timedelta(days=1, hours=7)
        a2 = Action.objects.create(ActionID=4,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=2),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=2),
                                   Destination=Location.objects.get(pk=1),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a2.Reservation.add(res)

        request = self.factory.get('/findAvailableEquipment/?actions[]=3,4&categoryid=1')
        response = reservationViews.findAvailableEquipment(request)
        self.assertEqual(response.status_code, 501)

    def test_b_starts_after_a1_ends_after_a2(self):
        res = Reservation.objects.create(pk=2,
                                         CustomerID=User.objects.get(pk=1),
                                         OwnerID=User.objects.get(pk=1),
                                         CustomerPhone="",
                                         CustomerEmail="",
                                         CustomerDept="",
                                         CustomerStatus="",
                                         ReservationNotes="",
                                         EventTitle="Second Test Reservation")

        start = timezone.now() + timedelta(days=1, hours=2)
        end = timezone.now() + timedelta(days=1, hours=3)
        a1 = Action.objects.create(ActionID=3,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=1),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=1),
                                   Destination=Location.objects.get(pk=2),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a1.Reservation.add(res)

        start = timezone.now() + timedelta(days=3, hours=0)
        end = timezone.now() + timedelta(days=3, hours=1)
        a2 = Action.objects.create(ActionID=4,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=2),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=2),
                                   Destination=Location.objects.get(pk=1),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a2.Reservation.add(res)

        request = self.factory.get('/findAvailableEquipment/?actions[]=3,4&categoryid=1')
        response = reservationViews.findAvailableEquipment(request)
        self.assertEqual(response.status_code, 501)

    def test_b_starts_before_a1_ends_after_a2(self):
        res = Reservation.objects.create(pk=2,
                                         CustomerID=User.objects.get(pk=1),
                                         OwnerID=User.objects.get(pk=1),
                                         CustomerPhone="",
                                         CustomerEmail="",
                                         CustomerDept="",
                                         CustomerStatus="",
                                         ReservationNotes="",
                                         EventTitle="Second Test Reservation")

        start = timezone.now() + timedelta(days=0, hours=1)
        end = timezone.now() + timedelta(days=0, hours=2)
        a1 = Action.objects.create(ActionID=3,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=1),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=1),
                                   Destination=Location.objects.get(pk=2),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a1.Reservation.add(res)

        start = timezone.now() + timedelta(days=3, hours=0)
        end = timezone.now() + timedelta(days=3, hours=1)
        a2 = Action.objects.create(ActionID=4,
                                   AssignedOperatorID=User.objects.get(pk=1),
                                   ActionTypeID=ActionType.objects.get(pk=2),
                                   StartTime=start,
                                   EndTime=end,
                                   Origin=Location.objects.get(pk=2),
                                   Destination=Location.objects.get(pk=1),
                                   ActionStatus="Incomplete",
                                   ActionNotes="This is action 1")
        a2.Reservation.add(res)

        request = self.factory.get('/findAvailableEquipment/?actions[]=3,4&categoryid=1')
        response = reservationViews.findAvailableEquipment(request)
        self.assertEqual(response.status_code, 501)

    def tearDown(self):
        pass
        #Action.objects.get(pk=3).delete()
        #Action.objects.get(pk=4).delete()
        #Reservation.objects.get(pk=2).delete()


text:
var Validator = require('jsonschema').Validator;
var v = new Validator();

var logger = require('../logger');

var moment = require('moment');

//Config file
config = require('../config');

var sampleJson = '{ "expenses" : [' +
		'{ "type":"type1" , "value":2, "date":"12/04/2015" },' +
		'{ "type":"type2" , "value":3, "date":"12/04/2015" },' +
		'{ "type":"type3" , "value":6, "date":"12/04/2015" } ]}';

/**
return  sample.
*/
function getSampleJson() {
	return sampleJson;
}

/**
Check if the json is valid.
*/
function isValid(jsonToParse) {
	var response = {
		isValid: true,
		errors: []
	}
	if(jsonToParse) {
		try {
			var expenses = JSON.parse(jsonToParse).expenses;
		} catch(err) {
			response.isValid = false;
			response.errors.push("Invalid Json Data");
			return response;
		}

		logger.info("expenses ", expenses);

		for(var i=0; i < expenses.length; i++) {
			var date = new Date(expenses[i].date);
			if(true === isNaN(date)) {
				//continue let the jsonschema library handle the error.
			} else {
				expenses[i].date = date;
			}
			var errors = v.validate(expenses[i], config.expenseSchema).errors;
			if(0 < errors.length) {
				response.isValid = false;
				for(var j = 0; j < errors.length; j++) {
					response.errors.push("line " + (i+1) + " : " + errors[j]);
				}

			}
		}
	} else {
		response.isValid = false;
		response.errors.push("Invalid Json Data");
	}
	return response;
}

/**
sort expenses by date.
*/
function getSortedExpenses(jsonData) {
	var expenses = JSON.parse(jsonData).expenses;
	for(var i=0; i < expenses.length; i++) {
		var date = new Date(expenses[i].date);
		expenses[i].date = moment(date).format('DD MMM YYYY');
	}
	expenses.sort(function(a, b){
		return a.date-b.date //sort by date ascending
	});
	return expenses;
}

module.exports = {
	getSampleJson: getSampleJson,
	isValid: isValid,
	getSortedExpenses: getSortedExpenses
}


text:
import re
from urlparse import urlparse
import requests # Yes, you need to install that
from app import cache

def validateform(username):

    if username==None:
        return None
    else:
        if username.startswith('http://') or username.startswith('https://'):
            try:
                username = urlparse(username).path.split('/')[-1]
            except IndexError:
                return None
        if not re.match(r'^(?!_)[a-zA-Z0-9_]+$',username):
            return None
        else:
            return username

@cache.memoize(timeout=172800)
def getnickname(username):
    r = requests.get("http://api.bgm.tv/user/"+username)
    return r.json()['nickname']

@cache.memoize(timeout=172800)
def getitemname(itemidx):
    r = requests.get("http://api.bgm.tv/subject/"+str(itemidx))
    j = r.json()
    if len(j['name_cn']):
        return j['name_cn']
    else:
        return j['name']


text:
"""
Extract minor planet orbital elements and discovery dates to json.

Orbital elements are extracted from the file MPCORB.DAT:
https://minorplanetcenter.net/iau/MPCORB/MPCORB.DAT
Discovery dates are extracted from the file NumberedMPs.txt:
https://minorplanetcenter.net/iau/lists/NumberedMPs.txt

Usage:
======
./data_to_json.py [-h] [-c] [N]

Parse orbital and discovery data to json.

positional arguments:
  N              maximum number of results

optional arguments:
  -h, --help     show this help message and exit
  -c, --compact  output as compact json format

TODO:
=====
- Get range between discovery dates
- Create an API (python server)
"""

OUTPUT_FILE = 'catalog.json'
MPCORB_FILE = 'MPCORB.DAT'
NUMMPS_FILE = 'NumberedMPs.txt'

import os, sys, json, argparse
from time import time
from datetime import datetime
from itertools import izip
from operator import itemgetter

# Change working directory to the module path
os.chdir(os.path.dirname(os.path.realpath(__file__)))

# Datetime to Julian date
def dt2jd(dt):
    dt = dt - datetime(2000, 1, 1)
    return dt.days + (dt.seconds + dt.microseconds / 1000000) / 86400 + 2451544.5

# Packed date to Datetime
def pd2dt(pd):
    y = int(str(int(pd[0], 36)) + pd[1:3])
    m = int(pd[3], 36)
    d = int(pd[4], 36)
    return datetime(y, m, d)

# Packed to Julian date
def pd2jd(pd):
    dt = pd2dt(pd)
    return dt2jd(dt)

def main(argv):
    # Parse argumanets
    parser = argparse.ArgumentParser(description='Parse orbital and discovery data to json.')
    parser.add_argument('amount', metavar='N', type=int, nargs='?', help='maximum number of results')
    parser.add_argument('-c', '--compact', action='store_true', dest='compact', help='output as compact json format')
    args = parser.parse_args()

    print 'Extracting MPC discovery dates and orbital elements ...'
    start_time = time()

    # Extract the discovery dates from NumberedMPs.txt
    # For a description of the format see https://minorplanetcenter.net/iau/lists/NumberedMPs000001.html

    mpcs_disc = {}

    for line in open(NUMMPS_FILE):
        nr = int(line[1:7].strip().replace('(', ''))
        # Extract the discovery date (YYYY MM DD) and convert it to Julian date
        date = datetime.strptime(line[41:51], '%Y %m %d')
        mpcs_disc[nr] = dt2jd(date)

    """
    Extract the orbital elements from MPCORB.DAT
    For a description of the format see https://minorplanetcenter.net/iau/info/MPOrbitFormat.html

    The following columns are extracted:

    epoch = Date for which the information is valid (packed date)
    a     = Semi-major axis (AU)
    e     = Orbital eccentricity (0..1)
    i     = Inclination to the ecliptic (degrees)
    W     = Longitude of ascending node (degrees)
    w     = Argument of perihelion (degrees)
    M     = Mean anomaly (degrees)
    n     = Mean daily motion (degrees per day)
    """

    mpcs = []
    count = 0

    for line in open(MPCORB_FILE):
        nr = line[167:173].strip().replace('(', '')
        if not nr: continue
        nr = int(nr)

        # Skip if discovery date is missing
        if nr not in mpcs_disc:
            print 'Skipping MPC #%d (no discovery date found)' % (nr)
            continue

        # Extract the orbital elements
        _, _, _, epoch, M, w, W, i, e, n, a, _ = line.split(None, 11)
        mpc = (mpcs_disc[nr], pd2jd(epoch), float(a), float(e), float(i), float(W), float(w), float(M), float(n))
        mpcs.append(mpc)

        # Maximum requested reached?
        count += 1
        if count == args.amount: break

    # Sort by discovery date
    mpcs.sort(key=itemgetter(0))

    if args.compact:
        output = mpcs
    else:
        keys = ['disc', 'epoch', 'a', 'e', 'i', 'W', 'w', 'M', 'n']
        output = [dict(izip(keys, mpc)) for mpc in mpcs]

    with open(OUTPUT_FILE, 'w') as outfile:
        json.dump(output, outfile)
        # json.dump(output, outfile, indent=2, separators=(',', ':'))

    print 'Finished extracting %d MPCs in %s seconds.' % (len(mpcs), time()-start_time)

if __name__ == '__main__':
    main(sys.argv[1:])


text:
package automenta.vivisect.swing.dock;

import java.awt.Point;
import java.awt.Rectangle;
import javax.swing.JComponent;
import javax.swing.JSplitPane;
import static javax.swing.SwingUtilities.convertPoint;

/**
 *
 * @author kitfox
 */
public class DockingRegionSplit extends JSplitPane
        implements DockingContainer, DockingChild {

    private DockingContainer dockParent;
    private DockingChild left;
    private DockingChild right;

    public DockingRegionSplit(DockingChild left, DockingChild right) {
        this.left = left;
        this.right = right;

//        setDividerSize(8);
        setLeftComponent(left.getComponent());
        setRightComponent(right.getComponent());
        left.setDockParent(this);
        right.setDockParent(this);

        //resetToPreferredSizes();
    }

    @Override
    public void resetToPreferredSizes() {
        super.resetToPreferredSizes();
    }

    @Override
    public JComponent getComponent() {
        return this;
    }

    @Override
    public DockingRegionSplit split(DockingChild child,
            DockingContent content, boolean splitRight, boolean vertical) {
        DockingRegionTabbed newRegion = new DockingRegionTabbed();
        newRegion.addTab(content);

        DockingChild splitLeftChild, splitRightChild;
        splitLeftChild = splitRight ? child : newRegion;
        splitRightChild = splitRight ? newRegion : child;

        DockingRegionSplit split = new DockingRegionSplit(splitLeftChild, splitRightChild);
        split.setOrientation(vertical ? JSplitPane.VERTICAL_SPLIT : JSplitPane.HORIZONTAL_SPLIT);
        split.setDividerLocation(vertical ? getHeight() / 2 : getWidth() / 2);
        split.setDockParent(this);

        int oldDivide = getDividerLocation();
        if (left == child) {
            setLeftComponent(split);
            left = split;
        } else if (right == child) {
            setRightComponent(split);
            right = split;
        } else {
            throw new IllegalArgumentException();
        }
        setDividerLocation(oldDivide);

        revalidate();
        return split;
    }

    /**
     * Called when oldChild is no longer valid and should be removed from the
     * docking layout.
     *
     * @param oldChild Child to remove
     * @param newChild Child to replace oldChild with, or null if pane should
     * simply be removed.
     */
    @Override
    public void join(DockingChild oldChild, DockingChild newChild) {
        if (left == oldChild) {
            if (newChild == null) {
                dockParent.join(this, right);
            } else {
                int divLoc = getDividerLocation();
                left = newChild;
                left.setDockParent(this);
                setLeftComponent(newChild.getComponent());
                setDividerLocation(divLoc);
            }
        } else if (right == oldChild) {
            if (newChild == null) {
                dockParent.join(this, left);
            } else {
                int divLoc = getDividerLocation();
                right = newChild;
                right.setDockParent(this);
                setRightComponent(newChild.getComponent());
                setDividerLocation(divLoc);
            }
        } else {
            throw new IllegalArgumentException();
        }
    }

    @Override
    public void addDockContent(DockingContent content) {
        left.addDockContent(content);
    }

    /**
     * @return the dockParent
     */
    @Override
    public DockingContainer getDockParent() {
        return dockParent;
    }

    /**
     * @param dockParent the dockParent to set
     */
    @Override
    public void setDockParent(DockingContainer dockParent) {
        this.dockParent = dockParent;
    }

    @Override
    public DockingPathRecord buildPath(DockingChild dockChild, DockingPathRecord childPath) {
        return dockParent.buildPath(this,
                new PathRecordSplit(childPath, right == dockChild));
    }

    @Override
    public DockingRegionContainer getContainerRoot() {
        return dockParent.getContainerRoot();
    }

    @Override
    public DockingChild getDockingChild(DockingPathRecord subpath) {
        if (subpath instanceof PathRecordSplit) {
            //Path still consitent.  Pass restore down to indicated child
            PathRecordSplit rec = (PathRecordSplit) subpath;
            if (rec.right) {
                return right.getDockingChild(subpath.next);
            } else {
                return left.getDockingChild(subpath.next);
            }
        } else {
            //We've lost the trail.  Just add in the content here
            return this;
        }
    }

    @Override
    public void restore(DockingContent content, DockingPathRecord subpath) {
        if (subpath instanceof PathRecordSplit) {
            //Path still consitent.  Pass restore down to indicated child
            PathRecordSplit rec = (PathRecordSplit) subpath;
            if (rec.right) {
                right.restore(content, subpath.next);
            } else {
                left.restore(content, subpath.next);
            }
        } else {
            //We've lost the trail.  Just add in the content here
            addDockContent(content);
        }
    }

    @Override
    public DockingPickRecord pickContainer(Point containerPoint) {
        {
            Point relPoint = convertPoint(this, containerPoint, leftComponent);
            Rectangle bounds = left.getComponent().getBounds();
            bounds.x = bounds.y = 0;
            if (bounds.contains(relPoint)) {
                return left.pickContainer(relPoint);
            }
        }

        {
            Point relPoint = convertPoint(this, containerPoint, rightComponent);
            Rectangle bounds = right.getComponent().getBounds();
            bounds.x = bounds.y = 0;
            if (bounds.contains(relPoint)) {
                return right.pickContainer(relPoint);
            }
        }

        return null;
    }

    /**
     * @return the left
     */
    public DockingChild getLeft() {
        return left;
    }

    /**
     * @return the right
     */
    public DockingChild getRight() {
        return right;
    }

    @Override
    public void closeAll() {
        left.closeAll();
        right.closeAll();
    }

    //---------------------------------
    public static class PathRecordSplit extends DockingPathRecord {

        boolean right;

        public PathRecordSplit(DockingPathRecord child, boolean right) {
            super(child);
            this.right = right;
        }

//        @Override
//        public DockingChild getDockingChild()
//        {
//            return DockingRegionSplit.this;
//        }
    }

}


text:
#pragma once
#include <aws/servicecatalog/ServiceCatalog_EXPORTS.h>
#include <aws/servicecatalog/model/ProductViewDetail.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/servicecatalog/model/ProvisioningArtifactSummary.h>
#include <aws/servicecatalog/model/Tag.h>
#include <aws/servicecatalog/model/TagOptionDetail.h>
#include <aws/servicecatalog/model/BudgetDetail.h>
#include <utility>

namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;

namespace Utils
{
namespace Json
{
  class JsonValue;
} // namespace Json
} // namespace Utils
namespace ServiceCatalog
{
namespace Model
{
  class AWS_SERVICECATALOG_API DescribeProductAsAdminResult
  {
  public:
    DescribeProductAsAdminResult();
    DescribeProductAsAdminResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
    DescribeProductAsAdminResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);

    /**
     *
Information about the product view.

     */
    inline const ProductViewDetail& GetProductViewDetail() const{ return m_productViewDetail; }

    /**
     *
Information about the product view.

     */
    inline void SetProductViewDetail(const ProductViewDetail& value) { m_productViewDetail = value; }

    /**
     *
Information about the product view.

     */
    inline void SetProductViewDetail(ProductViewDetail&& value) { m_productViewDetail = std::move(value); }

    /**
     *
Information about the product view.

     */
    inline DescribeProductAsAdminResult& WithProductViewDetail(const ProductViewDetail& value) { SetProductViewDetail(value); return *this;}

    /**
     *
Information about the product view.

     */
    inline DescribeProductAsAdminResult& WithProductViewDetail(ProductViewDetail&& value) { SetProductViewDetail(std::move(value)); return *this;}

    /**
     *
Information about the provisioning artifacts (also known as versions) for the
     * specified product.

     */
    inline const Aws::Vector<ProvisioningArtifactSummary>& GetProvisioningArtifactSummaries() const{ return m_provisioningArtifactSummaries; }

    /**
     *
Information about the provisioning artifacts (also known as versions) for the
     * specified product.

     */
    inline void SetProvisioningArtifactSummaries(const Aws::Vector<ProvisioningArtifactSummary>& value) { m_provisioningArtifactSummaries = value; }

    /**
     *
Information about the provisioning artifacts (also known as versions) for the
     * specified product.

     */
    inline void SetProvisioningArtifactSummaries(Aws::Vector<ProvisioningArtifactSummary>&& value) { m_provisioningArtifactSummaries = std::move(value); }

    /**
     *
Information about the provisioning artifacts (also known as versions) for the
     * specified product.

     */
    inline DescribeProductAsAdminResult& WithProvisioningArtifactSummaries(const Aws::Vector<ProvisioningArtifactSummary>& value) { SetProvisioningArtifactSummaries(value); return *this;}

    /**
     *
Information about the provisioning artifacts (also known as versions) for the
     * specified product.

     */
    inline DescribeProductAsAdminResult& WithProvisioningArtifactSummaries(Aws::Vector<ProvisioningArtifactSummary>&& value) { SetProvisioningArtifactSummaries(std::move(value)); return *this;}

    /**
     *
Information about the provisioning artifacts (also known as versions) for the
     * specified product.

     */
    inline DescribeProductAsAdminResult& AddProvisioningArtifactSummaries(const ProvisioningArtifactSummary& value) { m_provisioningArtifactSummaries.push_back(value); return *this; }

    /**
     *
Information about the provisioning artifacts (also known as versions) for the
     * specified product.

     */
    inline DescribeProductAsAdminResult& AddProvisioningArtifactSummaries(ProvisioningArtifactSummary&& value) { m_provisioningArtifactSummaries.push_back(std::move(value)); return *this; }

    /**
     *
Information about the tags associated with the product.

     */
    inline const Aws::Vector<Tag>& GetTags() const{ return m_tags; }

    /**
     *
Information about the tags associated with the product.

     */
    inline void SetTags(const Aws::Vector<Tag>& value) { m_tags = value; }

    /**
     *
Information about the tags associated with the product.

     */
    inline void SetTags(Aws::Vector<Tag>&& value) { m_tags = std::move(value); }

    /**
     *
Information about the tags associated with the product.

     */
    inline DescribeProductAsAdminResult& WithTags(const Aws::Vector<Tag>& value) { SetTags(value); return *this;}

    /**
     *
Information about the tags associated with the product.

     */
    inline DescribeProductAsAdminResult& WithTags(Aws::Vector<Tag>&& value) { SetTags(std::move(value)); return *this;}

    /**
     *
Information about the tags associated with the product.

     */
    inline DescribeProductAsAdminResult& AddTags(const Tag& value) { m_tags.push_back(value); return *this; }

    /**
     *
Information about the tags associated with the product.

     */
    inline DescribeProductAsAdminResult& AddTags(Tag&& value) { m_tags.push_back(std::move(value)); return *this; }

    /**
     *
Information about the TagOptions associated with the product.

     */
    inline const Aws::Vector<TagOptionDetail>& GetTagOptions() const{ return m_tagOptions; }

    /**
     *
Information about the TagOptions associated with the product.

     */
    inline void SetTagOptions(const Aws::Vector<TagOptionDetail>& value) { m_tagOptions = value; }

    /**
     *
Information about the TagOptions associated with the product.

     */
    inline void SetTagOptions(Aws::Vector<TagOptionDetail>&& value) { m_tagOptions = std::move(value); }

    /**
     *
Information about the TagOptions associated with the product.

     */
    inline DescribeProductAsAdminResult& WithTagOptions(const Aws::Vector<TagOptionDetail>& value) { SetTagOptions(value); return *this;}

    /**
     *
Information about the TagOptions associated with the product.

     */
    inline DescribeProductAsAdminResult& WithTagOptions(Aws::Vector<TagOptionDetail>&& value) { SetTagOptions(std::move(value)); return *this;}

    /**
     *
Information about the TagOptions associated with the product.

     */
    inline DescribeProductAsAdminResult& AddTagOptions(const TagOptionDetail& value) { m_tagOptions.push_back(value); return *this; }

    /**
     *
Information about the TagOptions associated with the product.

     */
    inline DescribeProductAsAdminResult& AddTagOptions(TagOptionDetail&& value) { m_tagOptions.push_back(std::move(value)); return *this; }

    /**
     *
Information about the associated budgets.

     */
    inline const Aws::Vector<BudgetDetail>& GetBudgets() const{ return m_budgets; }

    /**
     *
Information about the associated budgets.

     */
    inline void SetBudgets(const Aws::Vector<BudgetDetail>& value) { m_budgets = value; }

    /**
     *
Information about the associated budgets.

     */
    inline void SetBudgets(Aws::Vector<BudgetDetail>&& value) { m_budgets = std::move(value); }

    /**
     *
Information about the associated budgets.

     */
    inline DescribeProductAsAdminResult& WithBudgets(const Aws::Vector<BudgetDetail>& value) { SetBudgets(value); return *this;}

    /**
     *
Information about the associated budgets.

     */
    inline DescribeProductAsAdminResult& WithBudgets(Aws::Vector<BudgetDetail>&& value) { SetBudgets(std::move(value)); return *this;}

    /**
     *
Information about the associated budgets.

     */
    inline DescribeProductAsAdminResult& AddBudgets(const BudgetDetail& value) { m_budgets.push_back(value); return *this; }

    /**
     *
Information about the associated budgets.

     */
    inline DescribeProductAsAdminResult& AddBudgets(BudgetDetail&& value) { m_budgets.push_back(std::move(value)); return *this; }

  private:

    ProductViewDetail m_productViewDetail;

    Aws::Vector<ProvisioningArtifactSummary> m_provisioningArtifactSummaries;

    Aws::Vector<Tag> m_tags;

    Aws::Vector<TagOptionDetail> m_tagOptions;

    Aws::Vector<BudgetDetail> m_budgets;
  };

} // namespace Model
} // namespace ServiceCatalog
} // namespace Aws


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/np__more_list_item_container"
    android:layout_width="match_parent"
    android:layout_height="@dimen/np__more_list_item_content_height"
    android:background="@color/np__white"
    android:clickable="true"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingBottom="@dimen/np__more_list_item_top_bottom_padding"
    android:paddingLeft="@dimen/np__more_list_item_left_right_padding"
    android:paddingRight="@dimen/np__more_list_item_left_right_padding"
    android:paddingTop="@dimen/np__more_list_item_top_bottom_padding" >

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/np__grey_light" />

    <!--suppress UseCompoundDrawables, It's mor ecomplicated to controll the drawable layouting -->
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:gravity="center_vertical" >

        <ImageView
            android:id="@+id/np__more_list_item_icon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/np__more_list_item_content_left_margin"
            android:layout_marginStart="@dimen/np__more_list_item_content_left_margin" />

        <TextView
            android:id="@+id/np__more_list_item_text"
            style="@style/NP__.More.Item.Text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@dimen/np__more_list_item_content_left_margin"
            android:layout_marginStart="@dimen/np__more_list_item_content_left_margin" />
    </LinearLayout>

</RelativeLayout>


text:
codescanning
* Added cpp/diagnostics/failed-extractions. This query gives information about which extractions did not run to completion.


text:
/*****************************************************************************/
/**
* @file uart.c
*
* This file contains APIs for configuring the UART.
*
* <pre>
* MODIFICATION HISTORY:
*
* Ver   Who  Date     Changes
* ----- ---- -------- ---------------------------------------------------
* 5.00 	pkp  	 05/29/14 First release
* </pre>
*
* @note
*
* None.
*
******************************************************************************/

#include "xil_types.h"
#include "xil_assert.h"
#include "xil_io.h"
#include "xparameters.h"

/* Register offsets */
#define UART_CR_OFFSET		0x00000000U
#define UART_MR_OFFSET		0x00000004U
#define UART_BAUDGEN_OFFSET	0x00000018U
#define UART_BAUDDIV_OFFSET	0x00000034U

#define MAX_BAUD_ERROR_RATE	3U	/* max % error allowed */
#define UART_BAUDRATE	115200U
#define CSU_VERSION_REG     0xFFCA0044U

void Init_Uart(void);

void Init_Uart(void)
{
#ifdef STDOUT_BASEADDRESS
	u8 IterBAUDDIV;		/* Iterator for available baud divisor values */
	u32 BRGR_Value;		/* Calculated value for baud rate generator */
	u32 CalcBaudRate;	/* Calculated baud rate */
	u32 BaudError;		/* Diff between calculated and requested baud
				 * rate */
	u32 Best_BRGR = 0U;	/* Best value for baud rate generator */
	u8 Best_BAUDDIV = 0U;	/* Best value for baud divisor */
	u32 Best_Error = 0xFFFFFFFFU;
	u32 PercentError;
	u32 InputClk;
	u32 BaudRate = UART_BAUDRATE;

	/* set CD and BDIV */

#if (STDOUT_BASEADDRESS == XPAR_XUARTPS_0_BASEADDR)
	InputClk = XPAR_XUARTPS_0_UART_CLK_FREQ_HZ;
#elif (STDOUT_BASEADDRESS == XPAR_XUARTPS_1_BASEADDR)
	InputClk = XPAR_XUARTPS_1_UART_CLK_FREQ_HZ;
#else
	/* STDIO is not set or axi_uart is being used for STDIO */
	return;
#endif
InputClk = 25000000U;
	/*
	 * Determine the Baud divider. It can be 4to 254.
	 * Loop through all possible combinations
	 */
	for (IterBAUDDIV = 4U; IterBAUDDIV < 255U; IterBAUDDIV++) {

		/*
		 * Calculate the value for BRGR register
		 */
		BRGR_Value = InputClk / (BaudRate * ((u32)IterBAUDDIV + 1U));

		/*
		 * Calculate the baud rate from the BRGR value
		 */
		CalcBaudRate = InputClk/ (BRGR_Value * ((u32)IterBAUDDIV + 1U));

		/*
		 * Avoid unsigned integer underflow
		 */
		if (BaudRate > CalcBaudRate) {
			BaudError = BaudRate - CalcBaudRate;
		} else {
			BaudError = CalcBaudRate - BaudRate;
		}

		/*
		 * Find the calculated baud rate closest to requested baud rate.
		 */
		if (Best_Error > BaudError) {

			Best_BRGR = BRGR_Value;
			Best_BAUDDIV = IterBAUDDIV;
			Best_Error = BaudError;
		}
	}

	/*
	 * Make sure the best error is not too large.
	 */
	PercentError = (Best_Error * 100U) / BaudRate;
	if (((u32)MAX_BAUD_ERROR_RATE) < PercentError) {
		return;
	}

	/* set CD and BDIV */
	Xil_Out32(STDOUT_BASEADDRESS + UART_BAUDGEN_OFFSET, Best_BRGR);
	Xil_Out32(STDOUT_BASEADDRESS + UART_BAUDDIV_OFFSET, (u32)Best_BAUDDIV);

    /*
     * Veloce specific code
     */
    if((Xil_In32(CSU_VERSION_REG) & 0x0000F000U) == 0x00002000U ) {
	Xil_Out32(STDOUT_BASEADDRESS + UART_BAUDGEN_OFFSET, 2U);
	    Xil_Out32(STDOUT_BASEADDRESS + UART_BAUDDIV_OFFSET, 4U);
    }

	/*
	 * 8 data, 1 stop, 0 parity bits
	 * sel_clk=uart_clk=APB clock
	 */
	Xil_Out32(STDOUT_BASEADDRESS + UART_MR_OFFSET, 0x00000020U);

	/* enable Tx/Rx and reset Tx/Rx data path */
	Xil_Out32((STDOUT_BASEADDRESS + UART_CR_OFFSET), 0x00000017U);

	return;
#endif
}


text:
<?php declare(strict_types=1);

declare(strict_types = 1);

namespace DrdPlus\Tests\PropertiesByLevels;

use DrdPlus\Person\ProfessionLevels\ProfessionLevels;
use DrdPlus\PropertiesByLevels\NextLevelsProperties;
use DrdPlus\BaseProperties\Agility;
use DrdPlus\BaseProperties\Charisma;
use DrdPlus\BaseProperties\Intelligence;
use DrdPlus\BaseProperties\Knack;
use DrdPlus\BaseProperties\Strength;
use DrdPlus\BaseProperties\Will;
use Granam\Tests\Tools\TestWithMockery;

class NextLevelsPropertiesTest extends TestWithMockery
{
    /**
     * @test
     */
    public function I_can_get_properties()
    {
        $sut = new NextLevelsProperties($this->createProfessionLevels(
            $strength = 1, $agility = 2, $knack = 3, $will = 4, $intelligence = 5, $charisma = 6
        ));

        self::assertInstanceOf(Strength::class, $sut->getNextLevelsStrength());
        self::assertSame($strength, $sut->getNextLevelsStrength()->getValue());

        self::assertInstanceOf(Agility::class, $sut->getNextLevelsAgility());
        self::assertSame($agility, $sut->getNextLevelsAgility()->getValue());

        self::assertInstanceOf(Knack::class, $sut->getNextLevelsKnack());
        self::assertSame($knack, $sut->getNextLevelsKnack()->getValue());

        self::assertInstanceOf(Will::class, $sut->getNextLevelsWill());
        self::assertSame($will, $sut->getNextLevelsWill()->getValue());

        self::assertInstanceOf(Intelligence::class, $sut->getNextLevelsIntelligence());
        self::assertSame($intelligence, $sut->getNextLevelsIntelligence()->getValue());

        self::assertInstanceOf(Charisma::class, $sut->getNextLevelsCharisma());
        self::assertSame($charisma, $sut->getNextLevelsCharisma()->getValue());
    }

    /**
     * @param int $strength
     * @param int $agility
     * @param int $knack
     * @param int $will
     * @param int $intelligence
     * @param int $charisma
     * @return \Mockery\MockInterface|ProfessionLevels
     */
    private function createProfessionLevels($strength, $agility, $knack, $will, $intelligence, $charisma)
    {
        $professionLevels = $this->mockery(ProfessionLevels::class);
        $professionLevels->shouldReceive('getNextLevelsStrengthModifier')
            ->andReturn($strength);
        $professionLevels->shouldReceive('getNextLevelsAgilityModifier')
            ->andReturn($agility);
        $professionLevels->shouldReceive('getNextLevelsKnackModifier')
            ->andReturn($knack);
        $professionLevels->shouldReceive('getNextLevelsWillModifier')
            ->andReturn($will);
        $professionLevels->shouldReceive('getNextLevelsIntelligenceModifier')
            ->andReturn($intelligence);
        $professionLevels->shouldReceive('getNextLevelsCharismaModifier')
            ->andReturn($charisma);

        return $professionLevels;
    }
}


text:
namespace chrono {
namespace vehicle {
namespace man {

/// @addtogroup vehicle_models_man
/// @{

/// Simple MAN 5t driveline subsystem (purely kinematic).
class CH_MODELS_API MAN_5t_SimpleDriveline : public ChSimpleDriveline {
  public:
    MAN_5t_SimpleDriveline(const std::string& name);

    ~MAN_5t_SimpleDriveline() {}

    virtual double GetFrontTorqueFraction() const override { return m_front_torque_frac; }
    virtual double GetFrontDifferentialMaxBias() const override { return m_front_diff_bias; }
    virtual double GetRearDifferentialMaxBias() const override { return m_rear_diff_bias; }

  private:
    static const double m_front_torque_frac;
    static const double m_front_diff_bias;
    static const double m_rear_diff_bias;
};

/// @} vehicle_models_man

}  // namespace man
}  // end namespace vehicle
}  // end namespace chrono

#endif


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Caviar-Powered Web Page</title>

    This Web page is being served straight from an embed (attached) caviar
    bundle.

    Lorem Ipsum


text:
/*
 * Syntax coloring through Monokai CSS Theme for pygments
 * */

.highlight .hll { background-color: #49483e }
.highlight, .highlight pre  { background: #FAFAFA; border: none; }
.highlight  {

color: #ffffff ;

padding: 0.2em 0.9em;
  margin-bottom: 1em;
	font: normal normal normal 115%/normal 'Monaco', 'Courier New', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', monospace !important;
  line-height: 1.1em;
  overflow: auto;
	font-size: 1.0em;
	border: 1px solid #CCC;

	-moz-border-radius:7px;
	-webkit-border-radius:7px;
	border-radius:7px;

}

p > code, p > a > code
{
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
color: #C5CBD0;
/*color: white*/
background-image: url(/images/opaque_20.png);
font-family: Menlo, Consolas, "Courier New", Courier, "Liberation Mono", monospace;
font-size: 1.1em;
/*height: 0px;
image-rendering: auto;
left: auto;
list-style-type: disc;*/
padding-bottom: 2px;
padding-left: 4px;
padding-right: 4px;
padding-top: 2px;
text-decoration: none;
text-indent: 0px;
text-shadow: none;
text-transform: none;
top: auto;

}

p > a > code
{
color: #95be7d;
}

code, pre {
	font-family: "Consolas", "Courier New", "Courier", "FreeMono", monospace;
	font-size:0.95em;
	margin: 1em 0 1.5em 0;
}

.highlight span
{
font-family: "Consolas", "Courier New", "Courier", "FreeMono", monospace;
font-size:1em;
}

.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #00a8c8} /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #111111 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #111111 } /* Punctuation */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .kc { color: #00a8c8 } /* Keyword.Constant */
.highlight .kd { color: #00a8c8 } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #00a8c8 } /* Keyword.Pseudo */
.highlight .kr { color: #00a8c8 } /* Keyword.Reserved */
.highlight .kt { color: #00a8c8 } /* Keyword.Type */
.highlight .ld { color: #d88200 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #d88200} /* Literal.String */
.highlight .na { color: #75af00 } /* Name.Attribute */
.highlight .nb { color: #111111 } /* Name.Builtin */
.highlight .nc { color: #75af00 } /* Name.Class */
.highlight .no { color: #00a8c8 } /* Name.Constant */
.highlight .nd { color: #75af00 } /* Name.Decorator */
.highlight .ni { color: #111111 } /* Name.Entity */
.highlight .ne { color: #75af00 } /* Name.Exception */
.highlight .nf { color: #75af00} /* Name.Function */
.highlight .nl { color: #111111 } /* Name.Label */
.highlight .nn { color: #111111} /* Name.Namespace */
.highlight .nx { color: #75af00 } /* Name.Other */
.highlight .py { color: #111111 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #111111 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #111111 } /* Text.Whitespace */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sb { color: #d88200 } /* Literal.String.Backtick */
.highlight .sc { color: #d88200 } /* Literal.String.Char */
.highlight .sd { color: #d88200 } /* Literal.String.Doc */
.highlight .s2 { color: #d88200 } /* Literal.String.Double */
.highlight .se { color: #8045FF } /* Literal.String.Escape */
.highlight .sh { color: #d88200 } /* Literal.String.Heredoc */
.highlight .si { color: #d88200 } /* Literal.String.Interpol */
.highlight .sx { color: #d88200 } /* Literal.String.Other */
.highlight .sr { color: #d88200 } /* Literal.String.Regex */
.highlight .s1 { color: #d88200 } /* Literal.String.Single */
.highlight .ss { color: #d88200 } /* Literal.String.Symbol */
.highlight .bp { color: #111111 } /* Name.Builtin.Pseudo */
.highlight .vc { color: #111111 } /* Name.Variable.Class */
.highlight .vg { color: #111111 } /* Name.Variable.Global */
.highlight .vi { color: #111111 } /* Name.Variable.Instance */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html SYSTEM "about:legacy-compat">

    <title>phpDox - WatsonSdkPhp\Factories\WatsonFactory::setPassword</title>
    <link rel="stylesheet" type="text/css" href="../../css/style.css" media="screen"/>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>

/**phpDox

          Overview

          Namespaces

          Interfaces

          Classes

          Source

            Overview

            Classes

            WatsonSdkPhp\Factories

            WatsonFactory

setPassword

            Introduction

            Synopsis

            Parameter

            Source

WatsonSdkPhp\Factories\WatsonFactory::setPassword

Set password

Signature

          public function setPassword(null|string
        $password )

Parameters

$password
                —
                object

      Generated using phpDox 0.10.0 - Copyright (C) 2010 - 2017 by Arne Blankerts


text:
namespace lldb {

class LLDB_API SBAddress;
class LLDB_API SBBlock;
class LLDB_API SBBreakpoint;
class LLDB_API SBBreakpointLocation;
class LLDB_API SBBroadcaster;
class LLDB_API SBCommand;
class LLDB_API SBCommandInterpreter;
class LLDB_API SBCommandInterpreterRunOptions;
class LLDB_API SBCommandPluginInterface;
class LLDB_API SBCommandReturnObject;
class LLDB_API SBCommunication;
class LLDB_API SBCompileUnit;
class LLDB_API SBData;
class LLDB_API SBDebugger;
class LLDB_API SBDeclaration;
class LLDB_API SBError;
class LLDB_API SBEvent;
class LLDB_API SBEventList;
class LLDB_API SBExecutionContext;
class LLDB_API SBExpressionOptions;
class LLDB_API SBFileSpec;
class LLDB_API SBFileSpecList;
class LLDB_API SBFrame;
class LLDB_API SBFunction;
class LLDB_API SBHostOS;
class LLDB_API SBInstruction;
class LLDB_API SBInstructionList;
class LLDB_API SBLineEntry;
class LLDB_API SBListener;
class LLDB_API SBModule;
class LLDB_API SBModuleSpec;
class LLDB_API SBModuleSpecList;
class LLDB_API SBProcess;
class LLDB_API SBQueue;
class LLDB_API SBQueueItem;
class LLDB_API SBSection;
class LLDB_API SBSourceManager;
class LLDB_API SBStream;
class LLDB_API SBStringList;
class LLDB_API SBSymbol;
class LLDB_API SBSymbolContext;
class LLDB_API SBSymbolContextList;
class LLDB_API SBTarget;
class LLDB_API SBThread;
class LLDB_API SBThreadCollection;
class LLDB_API SBThreadPlan;
class LLDB_API SBType;
class LLDB_API SBTypeCategory;
class LLDB_API SBTypeEnumMember;
class LLDB_API SBTypeEnumMemberList;
class LLDB_API SBTypeFilter;
class LLDB_API SBTypeFormat;
class LLDB_API SBTypeMemberFunction;
class LLDB_API SBTypeNameSpecifier;
class LLDB_API SBTypeSummary;
class LLDB_API SBTypeSummaryOptions;
#ifndef LLDB_DISABLE_PYTHON
class LLDB_API SBTypeSynthetic;
#endif
class LLDB_API SBTypeList;
class LLDB_API SBValue;
class LLDB_API SBValueList;
class LLDB_API SBWatchpoint;
class LLDB_API SBUnixSignals;

}

#endif  // LLDB_SBDefines_h_


text:
/**
 * @file
 * @brief 	Error class
 */

#ifndef __PULSAR_ERROR_H
#define __PULSAR_ERROR_H

#include <kernel/status.h>

#include <CoreDefs.h>
#include <exception>

namespace pulsar
{

	/**
	 * Base class for erros
	 */
	class PULSAR_PUBLIC BaseError : public std::exception
	{
		public:
			virtual const char *GetDescription() const throw() = 0;
			virtual const char *GetRecoverySuggestion() const throw();

		private:
			const char *what() const throw();
	};

	/**
	 * Class providing information on an error.
	 *
	 * THis class is used to report errors from API functions. It is a wrapper
	 * around status_t which allows information to be obtained about an error,
	 * such as a human-redable error description and sugestions for recovering
	 * from an error.
	 *
	 * The suggested method for using this class in classes not designed to be
	 * used from multiple threads simultaneously is to return a bool stating
	 * whether or not the function succeeded, and to have a GetError function
	 * that returns a reference to an error object giving details of the error.
	 * The suggested method for using this class in classes designed to be used
	 * from multiple threads simultaneously is to return a bool stating whether
	 * or not the function succeeded, and take an optional pointer to an Error
	 * object in which error information will be stored.
	 */
	class PULSAR_PUBLIC Error : public BaseError
	{
		public:
			Error() throw() : m_code(STATUS_SUCCESS) {}
			Error(status_t code) throw() : m_code(code) {}

			bool operator ==(Error &other) const throw() { return other.m_code == m_code; }
			bool operator ==(status_t code) const throw() { return code == m_code; }

			/**
			 * Get the status code.
			 *
			 * @return COde describing the error
			 */
			status_t GetCode() const throw() { return m_code; }

			virtual const char *GetDescription() const throw();
			virtual const char *GetRecoverySuggestion() const throw();

		private:
			status_t m_code;	// Status code
	};
}

#endif // __PULSAR_ERROR_H


text:
<dom-element id="email-reader">

  <template>
    <!-- <iframe sandbox height="100%" width="100%" srcdoc="{{email.body}}"></iframe> -->
  </template>

  <script>
    Polymer({
      is: 'email-reader'
    })
  </script>

</dom-element>


text:
package org.sisioh.aws4s.sns.model

import com.amazonaws.services.sns.model.CreatePlatformEndpointRequest
import org.sisioh.aws4s.PimpedType

import scala.collection.JavaConverters._

object CreatePlatformEndpointRequestFactory {

  def create(): CreatePlatformEndpointRequest =
    new CreatePlatformEndpointRequest()

}

class RichCreatePlatformEndpointRequest(val underlying: CreatePlatformEndpointRequest)
    extends AnyVal
    with PimpedType[CreatePlatformEndpointRequest] {

  def platformApplicationArnOpt: Option[String] =
    Option(underlying.getPlatformApplicationArn)

  def platformApplicationArnOpt_=(value: Option[String]): Unit =
    underlying.withPlatformApplicationArn(value.orNull)

  def withPlatformApplicationArnOpt(value: Option[String]): CreatePlatformEndpointRequest =
    underlying.withPlatformApplicationArn(value.orNull)

  def tokenOpt: Option[String] =
    Option(underlying.getToken)

  def tokenOpt_=(value: Option[String]): Unit =
    underlying.setToken(value.orNull)

  def withTokenOpt(token: Option[String]): CreatePlatformEndpointRequest =
    underlying.withToken(token.orNull)

  def customUserDataOpt: Option[String] =
    Option(underlying.getCustomUserData)

  def customUserDataOpt_=(value: Option[String]): Unit =
    underlying.setCustomUserData(value.orNull)

  def withCustomUserDataOpt(value: Option[String]): CreatePlatformEndpointRequest =
    underlying.withCustomUserData(value.orNull)

  def attributes: Map[String, String] =
    underlying.getAttributes.asScala.toMap

  def attributes_=(value: Map[String, String]): Unit =
    underlying.setAttributes(value.asJava)

  def withAttributes(attributes: Map[String, String]): CreatePlatformEndpointRequest =
    underlying.withAttributes(attributes.asJava)

}


text:
<!doctype html><title>Minimal tQuery Page</title>
<script src="../../../build/tquery-bundle.js"></script>

<script src="../../../vendor/three.js/examples/js/postprocessing/EffectComposer.js"></script>
<script src="../../../vendor/three.js/examples/js/postprocessing/BloomPass.js"></script>
<script src="../../../vendor/three.js/examples/js/postprocessing/DotScreenPass.js"></script>
<script src="../../../vendor/three.js/examples/js/postprocessing/FilmPass.js"></script>
<script src="../../../vendor/three.js/examples/js/postprocessing/MaskPass.js"></script>
<script src="../../../vendor/three.js/examples/js/postprocessing/RenderPass.js"></script>
<script src="../../../vendor/three.js/examples/js/postprocessing/SavePass.js"></script>
<script src="../../../vendor/three.js/examples/js/postprocessing/ShaderPass.js"></script>
<script src="../../../vendor/three.js/examples/js/postprocessing/TexturePass.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/BleachBypassShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/BlendShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/CopyShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/ColorifyShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/ConvolutionShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/FilmShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/FXAAShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/HorizontalBlurShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/SepiaShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/VerticalBlurShader.js"></script>
<script src="../../../vendor/three.js/examples/js/shaders/VignetteShader.js"></script>
<script src="../../pproc/tquery.effectcomposer.js"></script>

<body><script>
	var world	= tQuery.createWorld().boilerplate().start();
	var object	= tQuery.createTorus().addTo(world);

	//world.addEffectComposer().sepia().film(0.25, 0.25, 648, false).vignette().finish();
	//world.addEffectComposer().vignette().finish();

	var composer	= tQuery.createEffectComposer().renderPass();
	composer.sepia()
	//composer.bleachbypass()
	//composer.verticalBlur(1.1)
	//composer.horizontalBlur(1.1)
	//composer.motionBlur(0.9);
	//composer.fxaa();
	//composer.colorify();
	//composer.bloom(0.2)
	composer.film(0.25, 0.25, 648, false)
	//composer.screen();
	composer.vignette();
	composer.finish();
</script></body>


text:
Page Contents

Back to top


text:
from __future__ import absolute_import

import pickle
import socket

from copy import copy

from kombu import Connection, Consumer, Producer, parse_url
from kombu.connection import Resource
from kombu.five import items, range

from .case import Case, Mock, SkipTest, patch, skip_if_not_module
from .mocks import Transport

class test_connection_utils(Case):

    def setup(self):
        self.url = 'amqp://user:pass@localhost:5672/my/vhost'
        self.nopass = 'amqp://user:**@localhost:5672/my/vhost'
        self.expected = {
            'transport': 'amqp',
            'userid': 'user',
            'password': 'pass',
            'hostname': 'localhost',
            'port': 5672,
            'virtual_host': 'my/vhost',
        }

    def test_parse_url(self):
        result = parse_url(self.url)
        self.assertDictEqual(result, self.expected)

    def test_parse_generated_as_uri(self):
        conn = Connection(self.url)
        info = conn.info()
        for k, v in self.expected.items():
            self.assertEqual(info[k], v)
        # by default almost the same- no password
        self.assertEqual(conn.as_uri(), self.nopass)
        self.assertEqual(conn.as_uri(include_password=True), self.url)

    def test_as_uri_when_prefix(self):
        conn = Connection('memory://')
        conn.uri_prefix = 'foo'
        self.assertTrue(conn.as_uri().startswith('foo+memory://'))

    @skip_if_not_module('pymongo')
    def test_as_uri_when_mongodb(self):
        x = Connection('mongodb://localhost')
        self.assertTrue(x.as_uri())

    def test_bogus_scheme(self):
        with self.assertRaises(KeyError):
            Connection('bogus://localhost:7421').transport

    def assert_info(self, conn, **fields):
        info = conn.info()
        for field, expected in items(fields):
            self.assertEqual(info[field], expected)

    def test_rabbitmq_example_urls(self):
        # see Appendix A of http://www.rabbitmq.com/uri-spec.html

        self.assert_info(
            Connection('amqp://user:pass@host:10000/vhost'),
            userid='user', password='pass', hostname='host',
            port=10000, virtual_host='vhost',
        )

        self.assert_info(
            Connection('amqp://user%61:%61pass@ho%61st:10000/v%2fhost'),
            userid='usera', password='apass', hostname='hoast',
            port=10000, virtual_host='v/host',
        )

        self.assert_info(
            Connection('amqp://'),
            userid='guest', password='guest', hostname='localhost',
            port=5672, virtual_host='/',
        )

        self.assert_info(
            Connection('amqp://:@/'),
            userid='guest', password='guest', hostname='localhost',
            port=5672, virtual_host='/',
        )

        self.assert_info(
            Connection('amqp://user@/'),
            userid='user', password='guest', hostname='localhost',
            port=5672, virtual_host='/',
        )

        self.assert_info(
            Connection('amqp://user:pass@/'),
            userid='user', password='pass', hostname='localhost',
            port=5672, virtual_host='/',
        )

        self.assert_info(
            Connection('amqp://host'),
            userid='guest', password='guest', hostname='host',
            port=5672, virtual_host='/',
        )

        self.assert_info(
            Connection('amqp://:10000'),
            userid='guest', password='guest', hostname='localhost',
            port=10000, virtual_host='/',
        )

        self.assert_info(
            Connection('amqp:///vhost'),
            userid='guest', password='guest', hostname='localhost',
            port=5672, virtual_host='vhost',
        )

        self.assert_info(
            Connection('amqp://host/'),
            userid='guest', password='guest', hostname='host',
            port=5672, virtual_host='/',
        )

        self.assert_info(
            Connection('amqp://host/%2f'),
            userid='guest', password='guest', hostname='host',
            port=5672, virtual_host='/',
        )

    def test_url_IPV6(self):
        raise SkipTest("urllib can't parse ipv6 urls")

        self.assert_info(
            Connection('amqp://[::1]'),
            userid='guest', password='guest', hostname='[::1]',
            port=5672, virtual_host='/',
        )

class test_Connection(Case):

    def setup(self):
        self.conn = Connection(port=5672, transport=Transport)

    def test_establish_connection(self):
        conn = self.conn
        conn.connect()
        self.assertTrue(conn.connection.connected)
        self.assertEqual(conn.host, 'localhost:5672')
        channel = conn.channel()
        self.assertTrue(channel.open)
        self.assertEqual(conn.drain_events(), 'event')
        _connection = conn.connection
        conn.close()
        self.assertFalse(_connection.connected)
        self.assertIsInstance(conn.transport, Transport)

    def test_multiple_urls(self):
        conn1 = Connection('amqp://foo;amqp://bar')
        self.assertEqual(conn1.hostname, 'foo')
        self.assertListEqual(conn1.alt, ['amqp://foo', 'amqp://bar'])

        conn2 = Connection(['amqp://foo', 'amqp://bar'])
        self.assertEqual(conn2.hostname, 'foo')
        self.assertListEqual(conn2.alt, ['amqp://foo', 'amqp://bar'])

    def test_collect(self):
        connection = Connection('memory://')
        trans = connection._transport = Mock(name='transport')
        _collect = trans._collect = Mock(name='transport._collect')
        _close = connection._close = Mock(name='connection._close')
        connection.declared_entities = Mock(name='decl_entities')
        uconn = connection._connection = Mock(name='_connection')
        connection.collect()

        self.assertFalse(_close.called)
        _collect.assert_called_with(uconn)
        connection.declared_entities.clear.assert_called_with()
        self.assertIsNone(trans.client)
        self.assertIsNone(connection._transport)
        self.assertIsNone(connection._connection)

    def test_collect_no_transport(self):
        connection = Connection('memory://')
        connection._transport = None
        connection._close = Mock()
        connection.collect()
        connection._close.assert_called_with()

        connection._close.side_effect = socket.timeout()
        connection.collect()

    def test_collect_transport_gone(self):
        connection = Connection('memory://')
        uconn = connection._connection = Mock(name='conn._conn')
        trans = connection._transport = Mock(name='transport')
        collect = trans._collect = Mock(name='transport._collect')

        def se(conn):
            connection._transport = None
        collect.side_effect = se

        connection.collect()
        collect.assert_called_with(uconn)
        self.assertIsNone(connection._transport)

    def test_uri_passthrough(self):
        transport = Mock(name='transport')
        with patch('kombu.connection.get_transport_cls') as gtc:
            gtc.return_value = transport
            transport.can_parse_url = True
            with patch('kombu.connection.parse_url') as parse_url:
                c = Connection('foo+mysql://some_host')
                self.assertEqual(c.transport_cls, 'foo')
                self.assertFalse(parse_url.called)
                self.assertEqual(c.hostname, 'mysql://some_host')
                self.assertTrue(c.as_uri().startswith('foo+'))
            with patch('kombu.connection.parse_url') as parse_url:
                c = Connection('mysql://some_host', transport='foo')
                self.assertEqual(c.transport_cls, 'foo')
                self.assertFalse(parse_url.called)
                self.assertEqual(c.hostname, 'mysql://some_host')
        c = Connection('pyamqp+sqlite://some_host')
        self.assertTrue(c.as_uri().startswith('pyamqp+'))

    def test_default_ensure_callback(self):
        with patch('kombu.connection.logger') as logger:
            c = Connection(transport=Mock)
            c._default_ensure_callback(KeyError(), 3)
            self.assertTrue(logger.error.called)

    def test_ensure_connection_on_error(self):
        c = Connection('amqp://A;amqp://B')
        with patch('kombu.connection.retry_over_time') as rot:
            c.ensure_connection()
            self.assertTrue(rot.called)

            args = rot.call_args[0]
            cb = args[4]
            intervals = iter([1, 2, 3, 4, 5])
            self.assertEqual(cb(KeyError(), intervals, 0), 0)
            self.assertEqual(cb(KeyError(), intervals, 1), 1)
            self.assertEqual(cb(KeyError(), intervals, 2), 0)
            self.assertEqual(cb(KeyError(), intervals, 3), 2)
            self.assertEqual(cb(KeyError(), intervals, 4), 0)
            self.assertEqual(cb(KeyError(), intervals, 5), 3)
            self.assertEqual(cb(KeyError(), intervals, 6), 0)
            self.assertEqual(cb(KeyError(), intervals, 7), 4)

            errback = Mock()
            c.ensure_connection(errback=errback)
            args = rot.call_args[0]
            cb = args[4]
            self.assertEqual(cb(KeyError(), intervals, 0), 0)
            self.assertTrue(errback.called)

    def test_supports_heartbeats(self):
        c = Connection(transport=Mock)
        c.transport.implements.heartbeats = False
        self.assertFalse(c.supports_heartbeats)

    def test_is_evented(self):
        c = Connection(transport=Mock)
        c.transport.implements.async = False
        self.assertFalse(c.is_evented)

    def test_register_with_event_loop(self):
        c = Connection(transport=Mock)
        loop = Mock(name='loop')
        c.register_with_event_loop(loop)
        c.transport.register_with_event_loop.assert_called_with(
            c.connection, loop,
        )

    def test_manager(self):
        c = Connection(transport=Mock)
        self.assertIs(c.manager, c.transport.manager)

    def test_copy(self):
        c = Connection('amqp://example.com')
        self.assertEqual(copy(c).info(), c.info())

    def test_copy_multiples(self):
        c = Connection('amqp://A.example.com;amqp://B.example.com')
        self.assertTrue(c.alt)
        d = copy(c)
        self.assertEqual(d.alt, c.alt)

    def test_switch(self):
        c = Connection('amqp://foo')
        c._closed = True
        c.switch('redis://example.com//3')
        self.assertFalse(c._closed)
        self.assertEqual(c.hostname, 'example.com')
        self.assertEqual(c.transport_cls, 'redis')
        self.assertEqual(c.virtual_host, '/3')

    def test_maybe_switch_next(self):
        c = Connection('amqp://foo;redis://example.com//3')
        c.maybe_switch_next()
        self.assertFalse(c._closed)
        self.assertEqual(c.hostname, 'example.com')
        self.assertEqual(c.transport_cls, 'redis')
        self.assertEqual(c.virtual_host, '/3')

    def test_maybe_switch_next_no_cycle(self):
        c = Connection('amqp://foo')
        c.maybe_switch_next()
        self.assertFalse(c._closed)
        self.assertEqual(c.hostname, 'foo')
        self.assertIn(c.transport_cls, ('librabbitmq', 'pyamqp', 'amqp'))

    def test_heartbeat_check(self):
        c = Connection(transport=Transport)
        c.transport.heartbeat_check = Mock()
        c.heartbeat_check(3)
        c.transport.heartbeat_check.assert_called_with(c.connection, rate=3)

    def test_completes_cycle_no_cycle(self):
        c = Connection('amqp://')
        self.assertTrue(c.completes_cycle(0))
        self.assertTrue(c.completes_cycle(1))

    def test_completes_cycle(self):
        c = Connection('amqp://a;amqp://b;amqp://c')
        self.assertFalse(c.completes_cycle(0))
        self.assertFalse(c.completes_cycle(1))
        self.assertTrue(c.completes_cycle(2))

    def test__enter____exit__(self):
        conn = self.conn
        context = conn.__enter__()
        self.assertIs(context, conn)
        conn.connect()
        self.assertTrue(conn.connection.connected)
        conn.__exit__()
        self.assertIsNone(conn.connection)
        conn.close()    # again

    def test_close_survives_connerror(self):

        class _CustomError(Exception):
            pass

        class MyTransport(Transport):
            connection_errors = (_CustomError,)

            def close_connection(self, connection):
                raise _CustomError('foo')

        conn = Connection(transport=MyTransport)
        conn.connect()
        conn.close()
        self.assertTrue(conn._closed)

    def test_close_when_default_channel(self):
        conn = self.conn
        conn._default_channel = Mock()
        conn._close()
        conn._default_channel.close.assert_called_with()

    def test_close_when_default_channel_close_raises(self):

        class Conn(Connection):

            @property
            def connection_errors(self):
                return (KeyError,)

        conn = Conn('memory://')
        conn._default_channel = Mock()
        conn._default_channel.close.side_effect = KeyError()

        conn._close()
        conn._default_channel.close.assert_called_with()

    def test_revive_when_default_channel(self):
        conn = self.conn
        defchan = conn._default_channel = Mock()
        conn.revive(Mock())

        defchan.close.assert_called_with()
        self.assertIsNone(conn._default_channel)

    def test_ensure_connection(self):
        self.assertTrue(self.conn.ensure_connection())

    def test_ensure_success(self):
        def publish():
            return 'foobar'

        ensured = self.conn.ensure(None, publish)
        self.assertEqual(ensured(), 'foobar')

    def test_ensure_failure(self):
        class _CustomError(Exception):
            pass

        def publish():
            raise _CustomError('bar')

        ensured = self.conn.ensure(None, publish)
        with self.assertRaises(_CustomError):
            ensured()

    def test_ensure_connection_failure(self):
        class _ConnectionError(Exception):
            pass

        def publish():
            raise _ConnectionError('failed connection')

        self.conn.transport.connection_errors = (_ConnectionError,)
        ensured = self.conn.ensure(self.conn, publish)
        with self.assertRaises(_ConnectionError):
            ensured()

    def test_autoretry(self):
        myfun = Mock()

        self.conn.transport.connection_errors = (KeyError,)

        def on_call(*args, **kwargs):
            myfun.side_effect = None
            raise KeyError('foo')

        myfun.side_effect = on_call
        insured = self.conn.autoretry(myfun)
        insured()

        self.assertTrue(myfun.called)

    def test_SimpleQueue(self):
        conn = self.conn
        q = conn.SimpleQueue('foo')
        self.assertIs(q.channel, conn.default_channel)
        chan = conn.channel()
        q2 = conn.SimpleQueue('foo', channel=chan)
        self.assertIs(q2.channel, chan)

    def test_SimpleBuffer(self):
        conn = self.conn
        q = conn.SimpleBuffer('foo')
        self.assertIs(q.channel, conn.default_channel)
        chan = conn.channel()
        q2 = conn.SimpleBuffer('foo', channel=chan)
        self.assertIs(q2.channel, chan)

    def test_Producer(self):
        conn = self.conn
        self.assertIsInstance(conn.Producer(), Producer)
        self.assertIsInstance(conn.Producer(conn.default_channel), Producer)

    def test_Consumer(self):
        conn = self.conn
        self.assertIsInstance(conn.Consumer(queues=[]), Consumer)
        self.assertIsInstance(conn.Consumer(queues=[],
                              channel=conn.default_channel), Consumer)

    def test__repr__(self):
        self.assertTrue(repr(self.conn))

    def test__reduce__(self):
        x = pickle.loads(pickle.dumps(self.conn))
        self.assertDictEqual(x.info(), self.conn.info())

    def test_channel_errors(self):

        class MyTransport(Transport):
            channel_errors = (KeyError, ValueError)

        conn = Connection(transport=MyTransport)
        self.assertTupleEqual(conn.channel_errors, (KeyError, ValueError))

    def test_connection_errors(self):

        class MyTransport(Transport):
            connection_errors = (KeyError, ValueError)

        conn = Connection(transport=MyTransport)
        self.assertTupleEqual(conn.connection_errors, (KeyError, ValueError))

class test_Connection_with_transport_options(Case):

    transport_options = {'pool_recycler': 3600, 'echo': True}

    def setup(self):
        self.conn = Connection(port=5672, transport=Transport,
                               transport_options=self.transport_options)

    def test_establish_connection(self):
        conn = self.conn
        self.assertEqual(conn.transport_options, self.transport_options)

class xResource(Resource):

    def setup(self):
        pass

class ResourceCase(Case):
    abstract = True

    def create_resource(self, limit, preload):
        raise NotImplementedError('subclass responsibility')

    def assertState(self, P, avail, dirty):
        self.assertEqual(P._resource.qsize(), avail)
        self.assertEqual(len(P._dirty), dirty)

    def test_setup(self):
        if self.abstract:
            with self.assertRaises(NotImplementedError):
                Resource()

    def test_acquire__release(self):
        if self.abstract:
            return
        P = self.create_resource(10, 0)
        self.assertState(P, 10, 0)
        chans = [P.acquire() for _ in range(10)]
        self.assertState(P, 0, 10)
        with self.assertRaises(P.LimitExceeded):
            P.acquire()
        chans.pop().release()
        self.assertState(P, 1, 9)
        [chan.release() for chan in chans]
        self.assertState(P, 10, 0)

    def test_acquire_prepare_raises(self):
        if self.abstract:
            return
        P = self.create_resource(10, 0)

        self.assertEqual(len(P._resource.queue), 10)
        P.prepare = Mock()
        P.prepare.side_effect = IOError()
        with self.assertRaises(IOError):
            P.acquire(block=True)
        self.assertEqual(len(P._resource.queue), 10)

    def test_acquire_no_limit(self):
        if self.abstract:
            return
        P = self.create_resource(None, 0)
        P.acquire().release()

    def test_replace_when_limit(self):
        if self.abstract:
            return
        P = self.create_resource(10, 0)
        r = P.acquire()
        P._dirty = Mock()
        P.close_resource = Mock()

        P.replace(r)
        P._dirty.discard.assert_called_with(r)
        P.close_resource.assert_called_with(r)

    def test_replace_no_limit(self):
        if self.abstract:
            return
        P = self.create_resource(None, 0)
        r = P.acquire()
        P._dirty = Mock()
        P.close_resource = Mock()

        P.replace(r)
        self.assertFalse(P._dirty.discard.called)
        P.close_resource.assert_called_with(r)

    def test_interface_prepare(self):
        if not self.abstract:
            return
        x = xResource()
        self.assertEqual(x.prepare(10), 10)

    def test_force_close_all_handles_AttributeError(self):
        if self.abstract:
            return
        P = self.create_resource(10, 10)
        cr = P.collect_resource = Mock()
        cr.side_effect = AttributeError('x')

        P.acquire()
        self.assertTrue(P._dirty)

        P.force_close_all()

    def test_force_close_all_no_mutex(self):
        if self.abstract:
            return
        P = self.create_resource(10, 10)
        P.close_resource = Mock()

        m = P._resource = Mock()
        m.mutex = None
        m.queue.pop.side_effect = IndexError

        P.force_close_all()

    def test_add_when_empty(self):
        if self.abstract:
            return
        P = self.create_resource(None, None)
        P._resource.queue[:] = []
        self.assertFalse(P._resource.queue)
        P._add_when_empty()
        self.assertTrue(P._resource.queue)

class test_ConnectionPool(ResourceCase):
    abstract = False

    def create_resource(self, limit, preload):
        return Connection(port=5672, transport=Transport).Pool(limit, preload)

    def test_setup(self):
        P = self.create_resource(10, 2)
        q = P._resource.queue
        self.assertIsNotNone(q[0]._connection)
        self.assertIsNotNone(q[1]._connection)
        self.assertIsNone(q[2]()._connection)

    def test_acquire_raises_evaluated(self):
        P = self.create_resource(1, 0)
        # evaluate the connection first
        r = P.acquire()
        r.release()
        P.prepare = Mock()
        P.prepare.side_effect = MemoryError()
        P.release = Mock()
        with self.assertRaises(MemoryError):
            with P.acquire():
                assert False
        P.release.assert_called_with(r)

    def test_release_no__debug(self):
        P = self.create_resource(10, 2)
        R = Mock()
        R._debug.side_effect = AttributeError()
        P.release_resource(R)

    def test_setup_no_limit(self):
        P = self.create_resource(None, None)
        self.assertFalse(P._resource.queue)
        self.assertIsNone(P.limit)

    def test_prepare_not_callable(self):
        P = self.create_resource(None, None)
        conn = Connection('memory://')
        self.assertIs(P.prepare(conn), conn)

    def test_acquire_channel(self):
        P = self.create_resource(10, 0)
        with P.acquire_channel() as (conn, channel):
            self.assertIs(channel, conn.default_channel)

class test_ChannelPool(ResourceCase):
    abstract = False

    def create_resource(self, limit, preload):
        return Connection(port=5672, transport=Transport) \
            .ChannelPool(limit, preload)

    def test_setup(self):
        P = self.create_resource(10, 2)
        q = P._resource.queue
        self.assertTrue(q[0].basic_consume)
        self.assertTrue(q[1].basic_consume)
        with self.assertRaises(AttributeError):
            getattr(q[2], 'basic_consume')

    def test_setup_no_limit(self):
        P = self.create_resource(None, None)
        self.assertFalse(P._resource.queue)
        self.assertIsNone(P.limit)

    def test_prepare_not_callable(self):
        P = self.create_resource(10, 0)
        conn = Connection('memory://')
        chan = conn.default_channel
        self.assertIs(P.prepare(chan), chan)


text: package io.joynr.messaging.bounceproxy.controller.runtime;