text:
<?php

namespace kartik\datecontrol;

use DateTime;
use DateTimeZone;
use Yii;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\helpers\FormatConverter;
use yii\base\InvalidConfigException;
use yii\web\View;
use yii\web\JsExpression;
use kartik\base\Config;

/**
 * DateControl widget enables you to control the formatting of date/time separately in View (display) and Model (save).
 *
 * @author Kartik Visweswaran <kartikv2@gmail.com>
 * @since 1.0
 */
class DateControl extends \kartik\base\InputWidget
{
    const FORMAT_DATE = 'date';
    const FORMAT_TIME = 'time';
    const FORMAT_DATETIME = 'datetime';

    /**
     * @inherit doc
     */
    protected $_pluginName = 'datecontrol';

    /**
     * @var string data type to use for the displayed date control. One of the FORMAT constants.
     */
    public $type = self::FORMAT_DATE;

    /**
     * @var boolean whether to use ajaxConversion to process date format for the widget.
     */
    public $ajaxConversion;

    /**
     * @var string the format string for displaying the date. If not set, will automatically use the settings
     * from the Module based on the `type` setting.
     */
    public $displayFormat;

    /**
     * @var string the default format string to be save the date as. If not set, will automatically use the settings
     * from the Module.
     */
    public $saveFormat;

    /**
     * @var string the timezone for the displayed date. If not set, no timezone
     * setting will be applied for formatting.
     * @see http://php.net/manual/en/timezones.php
     */
    public $displayTimezone;

    /**
     * @var string the timezone for the saved date. If not set, no timezone
     * setting will be applied for formatting.
     * @see http://php.net/manual/en/timezones.php
     */
    public $saveTimezone;

    /**
     * @var bool whether to automatically use \kartik\widgets based on `$type`. Will use these widgets:
     * - \kartik\date\DatePicker for FORMAT_DATE
     * - \kartik\time\TimePicker for FORMAT_TIME
     * - \kartik\datetime\DateTimePicker for FORMAT_DATETIME
     * If not set, this will default to `true.`
     */
    public $autoWidget;

    /**
     * @var string any custom widget class to use. Will only be used if autoWidget is set to `false`.
     */
    public $widgetClass;

    /**
     * @var array the HTML attributes for the display input. If a widget is used based on `autoWidget` or `widgetClass`,
     * this will be considered as the widget options.
     */
    public $options = [];

    /**
     * @var array the HTML attributes for the base model input that will be saved typically to database.
     * The following special options are recognized:
     * - 'type': string, whether to generate a 'hidden' or 'text' input. Defaults to 'hidden'.
     * - 'label': string, any label to be placed before the input. Will be only displayed if 'type' is 'text'.
     */
    public $saveOptions = [];

    /**
     * @var boolean whether to fire an asynchronous ajax request. Defaults to `true`.
     * You can set this to `false` for cases, where you need this to be fired synchronously.
     * For example when using this widget as a filter in \kartik\grid\GridView.
     */
    public $asyncRequest = true;

    /**
     * @var string display attribute name
     */
    protected $_displayAttribName;

    /**
     * @var \kartik\datecontrol\Module the `datecontrol` module instance
     */
    protected $_module;

    /**
     * @var array the parsed widget settings from the module
     */
    protected $_widgetSettings = [];

    /**
     * @var boolean whether translation is needed
     */
    private $_doTranslate = false;

    /**
     * @var array the english date settings
     */
    private $_enSettings = [
        'days' => ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
        'daysShort' => ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
        'months' => [
            'January',
            'February',
            'March',
            'April',
            'May',
            'June',
            'July',
            'August',
            'September',
            'October',
            'November',
            'December'
        ],
        'monthsShort' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        'meridiem' => ['AM', 'PM']
    ];

    /**
     * Initializes widget
     *
     * @throws \yii\base\InvalidConfigException
     */
    public function init()
    {
        $this->initConfig();
        if (!isset($this->ajaxConversion)) {
            $this->ajaxConversion = $this->_module->ajaxConversion;
        }
        if (!$this->ajaxConversion && ($this->displayTimezone != null || $this->saveTimezone != null)) {
            throw new InvalidConfigException("You must set 'ajaxConversion' to 'true' when using time-zones for display or save.");
        }
        parent::init();
        $this->setDataVar($this->_pluginName);
        $this->_displayAttribName = (($this->hasModel()) ? $this->attribute : $this->name) . '-' . $this->options['id'];
        $this->saveOptions['id'] = $this->options['id'];
        $this->options['id'] = $this->options['id'] . '-disp';
        $this->_doTranslate = isset($this->language) && $this->language != 'en';
        if ($this->_doTranslate && $this->autoWidget) {
            $this->_widgetSettings[$this->type]['options']['language'] = $this->language;
        }
        $this->setLocale();
    }

    /**
     * Initializes widget based on module settings
     *
     * @throws \yii\base\InvalidConfigException
     */
    protected function initConfig()
    {
        $this->_module = Config::initModule(Module::classname());
        if (!isset($this->autoWidget)) {
            $this->autoWidget = $this->_module->autoWidget;
        }
        if (!$this->autoWidget && !empty($this->widgetClass) && !class_exists($this->widgetClass)) {
            throw new InvalidConfigException("The widgetClass '{$this->widgetClass}' entered is invalid.");
        }
        if ($this->autoWidget === null) {
            $this->autoWidget = true;
        }
        $this->_widgetSettings = $this->_module->widgetSettings;
        if (empty($this->displayFormat)) {
            $this->displayFormat = $this->_module->getDisplayFormat($this->type);
        } else {
            $this->displayFormat = Module::parseFormat($this->displayFormat, $this->type);
        }
        if (empty($this->saveFormat)) {
            $this->saveFormat = $this->_module->getSaveFormat($this->type);
        } else {
            $this->saveFormat = Module::parseFormat($this->saveFormat, $this->type);
        }
        if (empty($this->displayTimezone)) {
            $this->displayTimezone = $this->_module->getDisplayTimezone();
        }
        if (empty($this->saveTimezone)) {
            $this->saveTimezone = $this->_module->getSaveTimezone();
        }
        if ($this->autoWidget) {
            $this->_widgetSettings = [
                self::FORMAT_DATE => ['class' => '\kartik\date\DatePicker'],
                self::FORMAT_DATETIME => ['class' => '\kartik\datetime\DateTimePicker'],
                self::FORMAT_TIME => ['class' => '\kartik\time\TimePicker'],
            ];
            Config::validateInputWidget($this->_widgetSettings[$this->type]['class'],
                "for DateControl '{$this->type}' format");
            foreach ($this->_widgetSettings as $type => $setting) {
                $this->_widgetSettings[$type]['options'] = $this->_module->autoWidgetSettings[$type];
                $this->_widgetSettings[$type]['disabled'] = $this->disabled;
                $this->_widgetSettings[$type]['readonly'] = $this->readonly;
            }
        }
        if (empty($this->widgetClass) && !empty($this->_widgetSettings[$this->type]['class'])) {
            $this->widgetClass = $this->_widgetSettings[$this->type]['class'];
        }
    }

    /**
     * Runs widget
     *
     * @return string|void
     */
    public function run()
    {
        $this->registerAssets();
        echo $this->getDisplayInput() . $this->getSaveInput();
        parent::run();
    }

    /**
     * Whether a widget is used to render the display
     *
     * @return bool
     */
    protected function isWidget()
    {
        return ($this->autoWidget || !empty($this->widgetClass));
    }

    /**
     * Generates the display input
     *
     * @return string
     */
    protected function getDisplayInput()
    {
        $value = empty($this->value) ? '' : $this->getDisplayValue($this->value);
        if (!$this->isWidget()) {
            if (empty($this->options['class'])) {
                $this->options['class'] = 'form-control';
            }
            return Html::textInput($this->_displayAttribName, $value, $this->options);
        }
        if (!empty($this->displayFormat) && $this->autoWidget) {
            $this->options = ArrayHelper::merge(Module::defaultWidgetOptions($this->type, $this->displayFormat),
                $this->options);
        }
        if (!empty($this->_widgetSettings[$this->type]['options'])) {
            $this->options = ArrayHelper::merge($this->_widgetSettings[$this->type]['options'], $this->options);
        }
        unset($this->options['model'], $this->options['attribute']);
        $this->options['name'] = $this->_displayAttribName;
        $this->options['value'] = $value;
        $class = $this->widgetClass;
        if (!property_exists($class, 'disabled')) {
            unset($this->options['disabled']);
        }
        if (!property_exists($class, 'readonly')) {
            unset($this->options['readonly']);
        }
        return $class::widget($this->options);
    }

    /**
     * Generates the save input
     *
     * @return string
     */
    protected function getSaveInput()
    {
        $type = ArrayHelper::remove($this->saveOptions, 'type', 'hidden');
        $label = ArrayHelper::remove($this->saveOptions, 'label', '');

        if ($type === 'text') {
            $this->saveOptions['tabindex'] = 10000;
            return $label . ($this->hasModel() ?
                Html::activeTextInput($this->model, $this->attribute, $this->saveOptions) :
                Html::textInput($this->name, $this->value, $this->saveOptions));
        }
        return $this->hasModel() ?
            Html::activeHiddenInput($this->model, $this->attribute, $this->saveOptions) :
            Html::hiddenInput($this->name, $this->value, $this->saveOptions);
    }

    /**
     * Gets the formatted display date value
     *
     * @param string $data the input date data
     *
     * @return string
     */
    protected function getDisplayValue($data)
    {
        //return Yii::$app->formatter->format($data, [$this->type, $this->displayFormat]);
        $date = DateTime::createFromFormat($this->saveFormat, $data);

        /**
         * Fix to prevent DateTime defaulting the time
         * part to current time, for FORMAT_DATE
         */
        $saveDate = $data;
        $saveFormat = $this->saveFormat;
        if ($this->type == self::FORMAT_DATE) {
            $saveDate .= " 00:00:00";
            $saveFormat .= " H:i:s";
        }

        if ($date instanceof DateTime) {
            if ($this->saveTimezone != null) {
                $date = DateTime::createFromFormat($saveFormat, $saveDate, new DateTimeZone($this->saveTimezone));
            } else {
                $date = DateTime::createFromFormat($saveFormat, $saveDate);
            }
        }
        if ($date instanceof DateTime) {
            if ($this->displayTimezone != null) {
                $date->setTimezone(new DateTimeZone($this->displayTimezone));
            }
            $value = $date->format($this->displayFormat);
            if ($this->_doTranslate) {
                $value = $this->translateDate($value, $this->displayFormat);
            }
            return $value;
        }
        return null;
    }

    /**
     * Translate the date string
     *
     * @param string $data the input date data
     * @param string $format the input date format
     *
     * @return string the translated date
     */
    protected function translateDate($data, $format)
    {
        $out = $data;
        if (strpos($format, 'F') > 0) { // long month
            $out = $this->translate($out, 'months');
        }
        if (strpos($format, 'l') > 0) { // long days
            $out = $this->translate($out, 'days');
        }
        if (strpos($format, 'M') > 0) { // short month
            $out = $this->translate($out, 'monthsShort');
        }
        if (strpos($format, 'D') > 0) { // short days
            $out = $this->translate($out, 'daysShort');
        }
        if (strpos($format, 'A') > 0) { // meridiem
            $out = $this->translate($out, 'meridiem');
        }
        if (strpos($format, 'a') > 0) { // meridiem
            $out = strtolower($this->translate($out, 'meridiem'));
        }
        return $out;
    }

    /**
     * Translate a date pattern based on type
     *
     * @param string $string input date string
     * @param string $type the type of date pattern as set in [[$_enSettings]]
     *
     * @return string the translated string
     */
    protected function translate($string, $type)
    {
        if (empty($this->pluginOptions['dateSettings'][$type])) {
            return $string;
        }
        $pairs = array_combine($this->_enSettings[$type], $this->pluginOptions['dateSettings'][$type]);
        return strtr($string, $pairs);
    }

    /**
     * Sets the locale using the locales configuration settings
     */
    protected function setLocale()
    {
        if (!$this->_doTranslate || !empty($this->pluginOptions['dateSettings'])) {
            return;
        }
        $s = DIRECTORY_SEPARATOR;
        $file = __DIR__ . "{$s}locales{$s}{$this->language}{$s}dateSettings.php";
        if (!file_exists($file)) {
            $langShort = Config::getLang($this->language);
            $file = __DIR__ . "{$s}locales{$s}$langShort{$s}dateSettings.php";
        }
        if (file_exists($file)) {
            $this->pluginOptions['dateSettings'] = require_once($file);
        }
    }

    /**
     * Registers assets
     */
    protected function registerAssets()
    {
        $view = $this->getView();
        DateFormatterAsset::register($view);
        DateControlAsset::register($view);
        $pluginOptions = empty($this->pluginOptions) ? [] : $this->pluginOptions;
        $this->pluginOptions = ArrayHelper::merge([
            'idSave' => $this->saveOptions['id'],
            'url' => $this->ajaxConversion ? Url::to([$this->_module->convertAction]) : '',
            'type' => $this->type,
            'saveFormat' => $this->saveFormat,
            'dispFormat' => $this->displayFormat,
            'saveTimezone' => $this->saveTimezone,
            'dispTimezone' => $this->displayTimezone,
            'asyncRequest' => $this->asyncRequest
        ], $pluginOptions);
        $this->registerPlugin($this->_pluginName);
        if ($this->isWidget() && !empty($this->options[$this->_dataVar])) {
            $this->options['options'][$this->_dataVar] = $this->options[$this->_dataVar];
            unset($this->options[$this->_dataVar]);
        }
    }
}


text:
<?php defined('BASEPATH') or exit('No direct script access allowed');

$lang['pages:page']                     = 'Page';
$lang['pages:pages']                    = 'Pages';

// tabs
$lang['pages:details_label']            = 'Page Details';
$lang['pages:content_label']            = 'Page Content';
$lang['pages:meta_label']               = 'Meta data';
$lang['pages:design_label']             = 'Design';
$lang['pages:script_label']             = 'Script';
$lang['pages:options_label']            = 'Options';
$lang['pages:detail_label']             = 'Details';

// label
$lang['pages:add_page_chunk']           = 'Add Page Chunk';
$lang['pages:page_chunk']               = 'Page Chunk';
$lang['pages:language_label']           = 'Language';
$lang['pages:updated_label']            = 'Updated';
$lang['pages:unknown_label']            = 'Unknown';
$lang['pages:navigation_label']         = 'Add to Navigation';
$lang['pages:body_label']               = 'Page body';
$lang['pages:meta_title_label']         = 'Meta title';
$lang['pages:meta_keywords_label']      = 'Meta keywords';
$lang['pages:meta_robots_no_index_label']	= 'Robots: Don\'t index this page:';
$lang['pages:meta_robots_no_follow_label']	= 'Robots: Don\'t follow links on this page:';
$lang['pages:meta_desc_label']          = 'Meta description';
$lang['pages:type_id_label']            = 'Page Type';
$lang['pages:css_label']                = 'CSS';
$lang['pages:js_label']                 = 'JavaScript';
$lang['pages:access_label']             = 'Access';
$lang['pages:rss_enabled_label']        = 'RSS enabled?';
$lang['pages:comments_enabled_label']   = 'Comments enabled?';
$lang['pages:is_home_label']            = 'Is default (home) page?';
$lang['pages:strict_uri_label']         = 'Require an exact uri match?';

$lang['pages:status_label']             = 'Status';
$lang['pages:draft_label']              = 'Draft';
$lang['pages:live_label']               = 'Live';
$lang['pages:revisions_label']          = 'Revisions';
$lang['pages:compare_label']            = 'Compare';
$lang['pages:preview_label']            = 'Preview';
$lang['pages:current_label']            = 'Current';
$lang['pages:view_label']               = 'View';
$lang['pages:create_label']             = 'Add child';
$lang['pages:duplicate_label']          = 'Duplicate';

// title
$lang['pages:create_title']             = 'Add Page';
$lang['pages:edit_title']               = 'Edit Page "%s"';
$lang['pages:list_title']               = 'Pages';
$lang['pages:choose_type_title']        = 'What type of page do you want to create?';
$lang['pages:types_create_title']       = 'Add Page Type';
$lang['pages:types_list_title']         = 'Types';

// messages
$lang['pages:no_pages']                 = 'There are no pages.';
$lang['pages:create_success']           = 'The page was created.';
$lang['pages:create_error']             = 'That page has not been created.';
$lang['pages:page_not_found_error']     = 'That page does not exist.';
$lang['pages:edit_success']             = 'The page "%s" was saved.';
$lang['pages:delete_home_error']        = 'You can not delete the home page!';
$lang['pages:delete_success']           = 'Page #%s has been deleted.';
$lang['pages:mass_delete_success']      = '%s pages have been deleted.';
$lang['pages:delete_none_notice']       = 'No pages were deleted.';
$lang['pages:page_already_exist_error'] = 'A page with the URL "%s" already exists in %s.';
$lang['pages:parent_not_exist_error']   = 'The parent page you have selected does not exist.';
$lang['pages:chunk_slug_length']        = 'Page Chunk slugs may be no more than 30 characters in length.';
$lang['pages:root_folder']              = 'the top level';

$lang['pages:tree_explanation_title']   = 'Explanation';
$lang['pages:tree_explanation']         = 'The list on the left represents pages on your website. Click the page item to show its children. You may drag pages to order them; drag horizontally to make it a child. When you click the page text you will see all sorts of handy information in this box.';
$lang['pages:rss_explanation']          = 'Enabling RSS for this page will give users a chance to subscribe to an RSS feed which shows each immediate page child as a new entry.';

redpajama_set_name: RedPajamaGithub


text:
__author__ = 'krishnaa'

import urllib2
import base64
import sys
import xml.etree.ElementTree as ET

def getVDC(url,authtoken,vdc_lookup,catalog):
    method = 'GET'
    handler = urllib2.HTTPSHandler()
    opener = urllib2.build_opener(handler)
    request = urllib2.Request(url)
    request.add_header("Accept",'application/*+xml;version=5.5')
    request.add_header("x-vcloud-authorization",authtoken)
    request.get_method = lambda: method
    try:
        connection = opener.open(request)
    except urllib2.HTTPError,e:
        connection = e

    if connection.code == 200:
        data = connection.read()
        #print "Data from ORG "
        #print "Data :", data
    else:
        print "ERROR", connection.code
        sys.exit(1)
    orgxml = ET.fromstring(data)
    #print "orging xml"
    orgxml = ET.fromstring(data)
    vdc = orgxml.findall("ns:Link",namespaces={'ns':'http://www.vmware.com/vcloud/v1.5'})
    #print len(vdc)
    orgc = []
    for i in vdc:
        dict = i.attrib
        if "application/vnd.vmware.vcloud.vdc+xml" and vdc_lookup in dict.values():
            if vdc_lookup in dict.values():
                vdc_dict = dict
        if "application/vnd.vmware.vcloud.catalog+xml" and catalog in dict.values():
            if catalog in dict.values():
                catalog_dict = dict

    return (vdc_dict,catalog_dict)


text:
import { Schema } from '../types/schema.ts'

export function lookupModality(schema: Schema, datatype: string): string {
  const modalities = schema.rules.modalities as Record<string, any>
  const datatypes = Object.keys(modalities).filter((key: string) => {
    modalities[key].datatypes.includes(datatype)
  })
  if (datatypes.length === 1) {
    return datatypes[0]
  } else if (datatypes.length === 0) {
    return ''
  } else {
    // what if multiple modalites are found?
    return ''
  }
}


text:
layout: blog
title: 'Adding GeoJSON to Leaflet with Link Relations'
---

**_Editor's note:_** _This post was updated in June 2014 to reflect changes in Leaflet and update examples to new versions. Shortly after publishing this post, I discovered [a different way](https://lyzidiamond.com/posts/external-geojson-and-leaflet-the-other-way/) to add GeoJSON to a Leaflet map that I like a lot better. You can read a blog post about that [here](https://lyzidiamond.com/posts/external-geojson-and-leaflet-the-other-way/)._

***

_Wednesday night, I was fortunate to attend the August meeting of PDX OSGEO, Portland's meetup for open source geo shenanigans. I learned some new stuff, got to see a [3D-printed map tile](https://www.mapbox.com/blog/weekend-hack-printing-3d-tiles/) (!!!!!), and got a chance to show off some of my recent work. The bulk of my contribution to the meeting was showing off a new technique for adding GeoJSON to a Leaflet map. This is an overview of what I talked about, with more detail and background._

[Leaflet](https://leafletjs.com) is one of the best mapping libraries out there; it's certainly my favorite! But one thing that's somewhat convoluted is adding and using GeoJSON layers inside your Leaflet map. The [Leaflet API](https://leafletjs.com/reference.html) does have a [constructor for adding a GeoJSON layer](https://leafletjs.com/reference.html#geojson), which is great! But when you have a GeoJSON file with hundreds or thousands of features, it makes most sense to house that data in an external file. The challenge then comes when trying to use or reference that file when constructing your map.

Let's look at an example. (This is the same example I used at the meeting.) A few months ago, my friend Liza tweeted at me:

@lyzidiamond You know maps, right? Is there a website that shows all the places in Portland where cupcakes can be purchased on map? #serious
— Liza J (@lizaface) May 17, 2013

And so, with all of my infinite free time*, I set off to construct a [GeoJSON file](https://github.com/lyzidiamond/lyzidiamond.github.com/blob/master/cupcakes.json) of places to buy cupcakes in Portland. _(Disclaimer: It's not comprehensive and it's not at all done, so expect it to change significantly and frequently.)_ But when I set off to create my map, I ran into the problem of referencing this file. How was I to assign the data to a variable such that I could use it in the L.geoJson constructor and add it as a layer to my map?

Typically when I have an issue like this, I turn to the best tech support at my disposal: Twitter.

Question: What is the best way to reference an external geojson file for use in a @LeafletJS map? Do I assign to a variable in the file?
— Lyzi Diamond (@lyzidiamond) August 4, 2013

The folks at Leaflet agreed that this would be the best way to go:

@lyzidiamond yep, it's the simplest way if you're including the GeoJSON statically on page load
— Leaflet (@LeafletJS) August 5, 2013

One of my Twitter friends, [Sean Gillies](https://twitter.com/sgillies), had another suggestion:

@lyzidiamond Fwiw, we use a typed link at ISAW: https://t.co/Ea2MzuchBV. If you don't want an extra request, you can use a data uri.
— Sean Gillies (@sgillies) August 4, 2013

I decided to play with this a little more, and it totally worked! And it worked well! So let's talk about it.

##GeoJSON: The Challenges

JSON and GeoJSON files are just JavaScript files. (JSON stands for JavaScript Object Notation; you can read more about JSON as a file type in a previous post, [here](https://lyzidiamond.com/posts/github-geojson/).) As such, you can reference a JSON or GeoJSON file as a script, the same way you would for, say, including the Leaflet or jQuery libraries in your code.

Adding a link to a script allows you access to its content; it's as if you copy-pasted the code in the script into your HTML file. Everything that is in that file is now effectively inside your HTML file and can be referenced and used freely. Adding the GeoJSON at the top does the same thing, but the GeoJSON data has no name. It's not attached to a variable. It's just features that can't be referenced, containing geometry and properties that can't be referenced. For the purposes of our map, it is essentially useless.

The obvious solution is to add a variable definition to our cupcakes.json file. That would mean that instead of this:

    {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [
              -122.65335738658904,
              45.512083676585156
            ]
          },
          "properties": {
              "name": "Hungry Heart Cupcakes",
              "address": "1212 SE Hawthorne Boulevard",
              "website": "https://www.hungryheartcupcakes.com",
              "gluten free": "no",
              "open1": "Monday - Sunday, 11am - 9pm"
          }
        },

    ...

we would have something like this:

    var cupcakes = {
      "type": "FeatureCollection",
      "features": [
        {
          "type": "Feature",
          "geometry": {
            "type": "Point",
            "coordinates": [
              -122.65335738658904,
              45.512083676585156
            ]
          },
          "properties": {
              "name": "Hungry Heart Cupcakes",
              "address": "1212 SE Hawthorne Boulevard",
              "website": "https://www.hungryheartcupcakes.com",
              "gluten free": "no",
              "open1": "Monday - Sunday, 11am - 9pm"
          }
        },

    ...

This would totally work, but it would mean that our cupcakes.json file would no longer be a true JSON/GeoJSON file. If you tried to [show the file in GitHub](https://lyzidiamond.com/posts/github-geojson-gets-better/), for example, the points would not be interpreted and a map would not be rendered. Additionally, you don't always have direct control over the GeoJSON file itself, especially if it's a shared dataset or if it's being returned from some other process. Adding a variable definition could also potentially mess up the work of anyone else trying to use your dataset, if it is indeed a dataset you constructed.

So what can you do? You can used a typed link/link relation and a little bit of jQuery. It's really quite magical.

##GeoJSON and Leaflet: The Solution

Let's look at the code, and then talk through it. You can view a live version of this [here](https://lyzidiamond.com/cupcakes.html).

      <link rel="stylesheet" href="https://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />

      <link rel="points" type="application/json" href=".cupcakes/cupcakes.json">

###The Head

Leaflet, as discussed previously, is a JavaScript mapping library with a lot of great functionality. (For more info on getting started with and using Leaflet, check out their [Quick Start Tutorial](https://leafletjs.com/examples/quick-start.html).) In order to use it, we need to include both a Leaflet CSS file (for map styling) and the Leaflet JavaScript file, which is what the stylesheet on line 3 and the script on line 8 are all about. Lines 4 through 7 are CSS rules to give our map a height and ensure that it is actually full-screen on the page.

    <link rel="stylesheet" href="https://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
    ...

The other library we need to make this work is called [jQuery](https://jquery.com/). jQuery is a JavaScript library that can make developing way easier, as it takes some of the complicated parts of the language and synthesizes them into easy-to-use pieces. Line 9 includes jQuery in our map, which allows us to use its functionality.

The interesting part comes at Line 10. This is where we are including our JSON** file using a [link relation](https://blog.whatwg.org/the-road-to-html-5-link-relations).

      <link rel="points" type="application/json" href=".cupcakes/cupcakes.json">

As defined on the WHATWG blog post to which I just linked, "Regular links simply point to another page. Link relations are a way to explain _why_ you're pointing to another page. They finish the sentence, 'I'm pointing to this other page because...'"

Typcailly, link relations are used with a common set of keywords that have specific value to the browser. For example, our CSS stylesheet on line 3 has the link relation `rel="stylesheet"`. This is the most common link relation, and every browser knows to download the data from the link before loading the page, as the relation tells it that the linked data contains important style information.

In our case, we are sort of hacking around that. We don't necessarily want the browser to fetch the data on load or at any particular time. Indeed, we don't want the browser to do anything with our GeoJSON file until we tell it to. Thus, we supply the link with a `rel="points"`, which isn't going to have any unintended consequences. (For more information on link relation keywords and what they do, check out [this comprehensive list](https://microformats.org/wiki/existing-rel-values).)

###The Body

Now let's get into the body of our HTML. The first think you see on line 13 is an empty div with id "cupcake-map." This is how Leaflet works: you create an empty div, and then write some JavaScript to fill it in. For us, this JavaScript starts on the very next line, as it's a full-screen web map.

Our JavaScript is sandwiched between `script` tags, which lets the browser know that anything inside of them is JavaScript and should be treated as such. (This was mirrored in lines 4 and 7 in the head, with `style` tags.) The first thing we do in our script (line 15) is define a variable called cupcakeTiles, and use the Leaflet [tileLayer](https://leafletjs.com/reference.html#tilelayer) constructor to define a map tile layer (more info on that at the link). This map uses custom tiles I made using [MapBox](https://mapbox.com), so this constructor links to those tiles. It also adds a property for maxZoom, ensuring that the map will not be zoomed in past zoom level 18. (For more information on web maps and zoom levels and how they work, check out [this blog post](https://lyzidiamond.com/posts/wtf-tilemill/).)

Line 19 is where the code gets interesting, as we employ jQuery's [getJSON method](https://api.jquery.com/jQuery.getJSON/). This method takes three parameters: A URL of the location of the data, a plain object or string that gets sent with the request for the data, and a function to execute if the request for data is successful. The second parameter is optional, and you'll see we don't actually use it in our example.

     $.getJSON($('link[rel="points"]').attr("href"), function(data) {

We pass `$('link[rel="points"]').attr("href")` as our first parameter, which actually _does_ translate to a URL. It finds a link by its rel value (`$('link[rel="points"]')`), and then uses a getter method [attr](https://api.jquery.com/attr/) to pull the value of the href parameter in the link. This returns `"./cupcakes.json"`, which is the location of our JSON file. (I should also note that our link has an attribute `type` that is defined as `'application/json'`. This helps the browser understand that the data in the link is JSON and should be treated as such.)

The second parameter is actually a function to be executed upon successful retrieval of data, called a _[callback function](https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/js-ctypes_reference/Callbacks)_. (If that blows your mind, take some time to read about [asynchronous programming](https://en.wikipedia.org/wiki/Asynchronous_I/O). It's really fascinating.) We actually have housed all the rest of the map creation and layer adding functionality of our map inside of this callback function, which ensures that the map won't draw unless the GeoJSON has successfully been retrieved.

Our callback function takes one parameter, `data`, which represents the data that will be returned from the getJSON method. The first thing the function does is create a variable `geojson` and use the Leaflet [geoJson](https://leafletjs.com/reference.html#geojson) constructor to define a _GeoJSON layer_. The constructor takes two parameters: one for the actual GeoJSON that will make the layer (`data`, in our case), and any options you wish to specify. One of these options is [onEachFeature](https://leafletjs.com/reference.html#geojson-oneachfeature), which we use to attach popups to our GeoJSON As the value for `onEachFeature`, we define a function that takes our data and adds a popup to each feature that shows whatever value is in that feature's `name` property.

    $.getJSON($('link[rel="points"]').attr("href"), function(data) {
        var geojson = L.geoJson(data, {
          onEachFeature: function (feature, layer) {
            layer.bindPopup(feature.properties.name);
          }
        });
    ...

After we have defined our GeoJSON layer, we have to actually create our map. This is done on line 23, where we create a variable `map` and use the Leaflet [map](https://leafletjs.com/reference.html#map-class) constructor to put our map in the `"cupcake-map"` div. We then also add a method [fitBounds()](https://leafletjs.com/reference.html#map-fitbounds) and pass it the extent of our GeoJSON data, which sets the bounds of our map to match the bounds of our data.

In the last two lines, we add our `cupcakeTiles` layer to the map and we add our geojson layer to the map.

    $.getJSON($('link[rel="points"]').attr("href"), function(data) {
      var geojson = L.geoJson(data, {
        onEachFeature: function (feature, layer) {
          layer.bindPopup(feature.properties.name);
        }
      });
      var map = L.map('cupcake-map').fitBounds(geojson.getBounds());
      cupcakeTiles.addTo(map);
      geojson.addTo(map);
    });

##We did it!

So what did we just do? We made a map with custom tiles that grabs GeoJSON from an external file without changing that file. Oh, and we added some popups to the GeoJSON features and set the bounds of our map to match the bounds of the data. Not too bad for 29 lines of code!

*This is a joke.

**JSON and GeoJSON are just JavaScript objects. A GeoJSON file can be saved as type .geojson, .json, or .js. All of them work.


text:
	import './support/gentypes';
	import { Proxy } from './support/proxy';

	export class TestStep  {

		___nsuri: string = "http://specmate.com/20190125/model/testspecification";
		public url: string;
		public className: string = "TestStep";
		public static className: string = "TestStep";
		// Attributes
		public id: EString;
		public name: EString;
		public description: EString;
		public position: EInt;
		public expectedOutcome: EString;

		// References
		public referencedTestParameters: Proxy[];

		// Containment

	}


text:
import rospy

import intera_interface

from intera_interface import CHECK_VERSION

class JointRecorder(object):
    def __init__(self, filename, rate, side="right"):
        """
        Records joint data to a file at a specified rate.
        """
        self.gripper_name = '_'.join([side, 'gripper'])
        self._filename = filename
        self._raw_rate = rate
        self._rate = rospy.Rate(rate)
        self._start_time = rospy.get_time()
        self._done = False

        self._limb_right = intera_interface.Limb(side)
        try:
            self._gripper = intera_interface.Gripper(self.gripper_name)
            rospy.loginfo("Electric gripper detected.")
        except Exception as e:
            self._gripper = None
            rospy.loginfo("No electric gripper detected.")

        # Verify Gripper Have No Errors and are Calibrated
        if self._gripper:
            if self._gripper.has_error():
                self._gripper.reboot()
            if not self._gripper.is_calibrated():
                self._gripper.calibrate()

        self._cuff = intera_interface.Cuff(side)

    def _time_stamp(self):
        return rospy.get_time() - self._start_time

    def stop(self):
        """
        Stop recording.
        """
        self._done = True

    def done(self):
        """
        Return whether or not recording is done.
        """
        if rospy.is_shutdown():
            self.stop()
        return self._done

    def record(self):
        """
        Records the current joint positions to a csv file if outputFilename was
        provided at construction this function will record the latest set of
        joint angles in a csv format.

        If a file exists, the function will overwrite existing file.
        """
        if self._filename:
            joints_right = self._limb_right.joint_names()
            with open(self._filename, 'w') as f:
                f.write('time,')
                temp_str = '' if self._gripper else '\n'
                f.write(','.join([j for j in joints_right]) + ',' + temp_str)
                if self._gripper:
                    f.write(self.gripper_name+'\n')
                while not self.done():
                    if self._gripper:
                        if self._cuff.upper_button():
                            self._gripper.open()
                        elif self._cuff.lower_button():
                            self._gripper.close()
                    angles_right = [self._limb_right.joint_angle(j)
                                    for j in joints_right]
                    f.write("%f," % (self._time_stamp(),))
                    f.write(','.join([str(x) for x in angles_right]) + ',' + temp_str)
                    if self._gripper:
                        f.write(str(self._gripper.get_position()) + '\n')
                    self._rate.sleep()


text:
//
//  graphgenerators.h
//  graphchi_xcode
//
//  Created by Aapo Kyrola on 9/16/13.
//
//

#ifndef __graphchi_xcode__graphgenerators__
#define __graphchi_xcode__graphgenerators__

#include <iostream>

#endif /* defined(__graphchi_xcode__graphgenerators__) */


text:
@interface LYURLCacheUtil : NSObject

+ (instancetype)sharedInstance;

- (CGFloat)getYPositionForURL:(NSString *)url;

- (void)insertURL:(NSString *)url yPosition:(CGFloat)yPosition;

@end


text:
import React from 'react';

import { SubmitASign } from '../../../src/containers/navigator/submit-a-sign';

describe('<SubmitASign />', () => {
  let wrapper;
  let isAuthenticatedBool;

  beforeEach(() => {
    isAuthenticatedBool = true;

    wrapper = shallow(<SubmitASign // eslint-disable-line react/jsx-filename-extension
      isAuthenticated={isAuthenticatedBool}
    />);
  });

  describe('mapDispatchToProps', () => {
    xit('dispatch are defined', () => {
    });
  });

  describe('when isAuthenticated is true', () => {
    it('renders element with button', () => {
      expect(wrapper.find('button').length).toBe(1);
      expect(wrapper.find('span').length).toBe(1);
    });

    it('labels the button with "Log Out"', () => {
      expect(wrapper.find('span').text()).toBe('Submit a Sign');
    });
  });

  describe('when isAuthenticated is false', () => {
    it('renders element without button', () => {
      isAuthenticatedBool = false;
      wrapper = shallow(<SubmitASign // eslint-disable-line react/jsx-filename-extension
        isAuthenticated={isAuthenticatedBool}
      />);

      expect(wrapper.find('button').length).toBe(0);
      expect(wrapper.find('span').length).toBe(1);
    });
  });
});


text:
    template<class V, class T> struct encode_type_impl<V, Fun(T)>\
    {\
        typedef\
            typename boost::type_of::encode_type<\
            typename boost::type_of::push_back<\
            V\
            , boost::type_of::constant<std::size_t,ID> >::type\
            , T>::type\
            type;\
    };\
    template<class Iter> struct decode_type_impl<boost::type_of::constant<std::size_t,ID>, Iter>\
    {\
        typedef boost::type_of::decode_type<Iter> d1;\
        typedef Fun(typename d1::type) type;\
        typedef typename d1::iter iter;\
    }

#define BOOST_TYPEOF_const_fun(T) const T
#define BOOST_TYPEOF_volatile_fun(T) volatile T
#define BOOST_TYPEOF_volatile_const_fun(T) volatile const T
#define BOOST_TYPEOF_pointer_fun(T) T*
#define BOOST_TYPEOF_reference_fun(T) T&

#if defined(__BORLANDC__) && !defined(__clang__) && (__BORLANDC__ < 0x600)
//Borland incorrectly handles T const, T const volatile and T volatile.
//It drops the decoration no matter what, so we need to try to handle T* const etc. without loosing the top modifier.
#define BOOST_TYPEOF_const_pointer_fun(T) T const *
#define BOOST_TYPEOF_const_reference_fun(T) T const &
#define BOOST_TYPEOF_volatile_pointer_fun(T) T volatile*
#define BOOST_TYPEOF_volatile_reference_fun(T) T volatile&
#define BOOST_TYPEOF_volatile_const_pointer_fun(T) T volatile const *
#define BOOST_TYPEOF_volatile_const_reference_fun(T) T volatile const &
#endif

BOOST_TYPEOF_BEGIN_ENCODE_NS

BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_const_fun);
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_volatile_fun);
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_volatile_const_fun);
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_pointer_fun);
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_reference_fun);

#if defined(__BORLANDC__) && !defined(__clang__) && (__BORLANDC__ < 0x600)
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_const_pointer_fun);
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_const_reference_fun);
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_volatile_pointer_fun);
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_volatile_reference_fun);
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_volatile_const_pointer_fun);
BOOST_TYPEOF_modifier_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_TYPEOF_volatile_const_reference_fun);
#endif

BOOST_TYPEOF_END_ENCODE_NS

#undef BOOST_TYPEOF_modifier_support
#undef BOOST_TYPEOF_const_fun
#undef BOOST_TYPEOF_volatile_fun
#undef BOOST_TYPEOF_volatile_const_fun
#undef BOOST_TYPEOF_pointer_fun
#undef BOOST_TYPEOF_reference_fun

#if defined(__BORLANDC__) && !defined(__clang__) && (__BORLANDC__ < 0x600)
#undef BOOST_TYPEOF_const_pointer_fun
#undef BOOST_TYPEOF_const_reference_fun
#undef BOOST_TYPEOF_volatile_pointer_fun
#undef BOOST_TYPEOF_volatile_reference_fun
#undef BOOST_TYPEOF_volatile_const_pointer_fun
#undef BOOST_TYPEOF_volatile_const_reference_fun
#endif

// arrays

#define BOOST_TYPEOF_array_support(ID, Qualifier)\
    template<class V, class T, int N>\
    struct encode_type_impl<V, Qualifier() T[N]>\
    {\
        typedef\
            typename boost::type_of::encode_type<\
            typename boost::type_of::push_back<\
            typename boost::type_of::push_back<\
            V\
            , boost::type_of::constant<std::size_t,ID> >::type\
            , boost::type_of::constant<std::size_t,N> >::type\
            , T>::type\
        type;\
    };\
    template<class Iter>\
    struct decode_type_impl<boost::type_of::constant<std::size_t,ID>, Iter>\
    {\
        enum{n = Iter::type::value};\
        typedef boost::type_of::decode_type<typename Iter::next> d;\
        typedef typename d::type Qualifier() type[n];\
        typedef typename d::iter iter;\
    }

BOOST_TYPEOF_BEGIN_ENCODE_NS

BOOST_TYPEOF_array_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_PP_EMPTY);
BOOST_TYPEOF_array_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_PP_IDENTITY(const));
BOOST_TYPEOF_array_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_PP_IDENTITY(volatile));
BOOST_TYPEOF_array_support(BOOST_TYPEOF_UNIQUE_ID(), BOOST_PP_IDENTITY(volatile const));
BOOST_TYPEOF_END_ENCODE_NS

#undef BOOST_TYPEOF_array_support

#endif//BOOST_TYPEOF_MODIFIERS_HPP_INCLUDED


text:
"""
Copyright (c) 2013, Regents of the University of California
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

  * Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

  * Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

  * Neither the name of the University of California nor the names of its
    contributors may be used to endorse or promote products derived from this
    software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

from unittest import TestCase

from pyramid import testing

from pushhubsearch.models import Root, SharedItems, SharedItem
from pushhubsearch.utils import remove_deleted_status
from .test_views import FakeSolr

class TestRemovalBase(TestCase):
    def setUp(self):
        self.config = testing.setUp()
        self.config.registry.settings['push.solr_uri'] = 'foo'
        self.root = Root()
        self.root.shared = SharedItems()
        item = SharedItem()
        uid = 'uuuuid'
        self.uid = uid
        item.__name__ = uid
        item.__parent__ = uid
        item.feed_type = ['selected', 'deleted']
        self.root.shared['uuuuid'] = item
        self.solr = FakeSolr()
        self.solr.catalog[uid] = [item]
        self.item = item

    def tearDown(self):
        testing.tearDown()
        self.root = None

class TestRemoveDeletedStatus(TestRemovalBase):
    def setUp(self):
        super(TestRemoveDeletedStatus, self).setUp()

    def test_remove_deleted(self):
        remove_deleted_status('uuuuid', self.root.shared, self.solr)
        self.assertTrue('deleted' not in self.item.feed_type)

class TestNotDeletedStatus(TestRemovalBase):
    def setUp(self):
        super(TestNotDeletedStatus, self).setUp()
        self.item.feed_type = ['shared', 'selected']
        self.solr.catalog[self.item.__name__][0].feed_type = self.item.feed_type

    def test_no_side_effects(self):
        remove_deleted_status('uuuuid', self.root.shared, self.solr)
        self.assertTrue('shared' in self.item.feed_type)
        self.assertTrue('selected' in self.item.feed_type)


text:
package org.apache.cassandra.utils;

import java.io.FileDescriptor;
import java.io.RandomAccessFile;
import java.lang.reflect.Field;
import java.nio.channels.FileChannel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jna.LastErrorException;
import com.sun.jna.Native;

public final class CLibrary
{
    private static final Logger logger = LoggerFactory.getLogger(CLibrary.class);

    private static final int MCL_CURRENT = 1;
    private static final int MCL_FUTURE = 2;

    private static final int ENOMEM = 12;

    private static final int F_GETFL   = 3;  /* get file status flags */
    private static final int F_SETFL   = 4;  /* set file status flags */
    private static final int F_NOCACHE = 48; /* Mac OS X specific flag, turns cache on/off */
    private static final int O_DIRECT  = 040000; /* fcntl.h */
    private static final int O_RDONLY  = 00000000; /* fcntl.h */

    private static final int POSIX_FADV_NORMAL     = 0; /* fadvise.h */
    private static final int POSIX_FADV_RANDOM     = 1; /* fadvise.h */
    private static final int POSIX_FADV_SEQUENTIAL = 2; /* fadvise.h */
    private static final int POSIX_FADV_WILLNEED   = 3; /* fadvise.h */
    private static final int POSIX_FADV_DONTNEED   = 4; /* fadvise.h */
    private static final int POSIX_FADV_NOREUSE    = 5; /* fadvise.h */

    static boolean jnaAvailable = true;
    static boolean jnaLockable = false;

    static
    {
        try
        {
            Native.register("c");
        }
        catch (NoClassDefFoundError e)
        {
            logger.warn("JNA not found. Native methods will be disabled.");
            jnaAvailable = false;
        }
        catch (UnsatisfiedLinkError e)
        {
            logger.warn("JNA link failure, one or more native method will be unavailable.");
            logger.debug("JNA link failure details: {}", e.getMessage());
        }
        catch (NoSuchMethodError e)
        {
            logger.warn("Obsolete version of JNA present; unable to register C library. Upgrade to JNA 3.2.7 or later");
            jnaAvailable = false;
        }
    }

    private static native int mlockall(int flags) throws LastErrorException;
    private static native int munlockall() throws LastErrorException;
    private static native int fcntl(int fd, int command, long flags) throws LastErrorException;
    private static native int posix_fadvise(int fd, long offset, int len, int flag) throws LastErrorException;
    private static native int open(String path, int flags) throws LastErrorException;
    private static native int fsync(int fd) throws LastErrorException;
    private static native int close(int fd) throws LastErrorException;

    private static int errno(RuntimeException e)
    {
        assert e instanceof LastErrorException;
        try
        {
            return ((LastErrorException) e).getErrorCode();
        }
        catch (NoSuchMethodError x)
        {
            logger.warn("Obsolete version of JNA present; unable to read errno. Upgrade to JNA 3.2.7 or later");
            return 0;
        }
    }

    private CLibrary() {}

    public static boolean jnaAvailable()
    {
        return jnaAvailable;
    }

    public static boolean jnaMemoryLockable()
    {
        return jnaLockable;
    }

    public static void tryMlockall()
    {
        try
        {
            mlockall(MCL_CURRENT);
            jnaLockable = true;
            logger.info("JNA mlockall successful");
        }
        catch (UnsatisfiedLinkError e)
        {
            // this will have already been logged by CLibrary, no need to repeat it
        }
        catch (RuntimeException e)
        {
            if (!(e instanceof LastErrorException))
                throw e;

            if (errno(e) == ENOMEM && System.getProperty("os.name").toLowerCase().contains("linux"))
            {
                logger.warn("Unable to lock JVM memory (ENOMEM)."
                        + " This can result in part of the JVM being swapped out, especially with mmapped I/O enabled."
                        + " Increase RLIMIT_MEMLOCK or run Cassandra as root.");
            }
            else if (!System.getProperty("os.name").toLowerCase().contains("mac"))
            {
                // OS X allows mlockall to be called, but always returns an error
                logger.warn("Unknown mlockall error {}", errno(e));
            }
        }
    }

    public static void trySkipCache(String path, long offset, long len)
    {
        trySkipCache(getfd(path), offset, len);
    }

    public static void trySkipCache(int fd, long offset, long len)
    {
        if (len == 0)
            trySkipCache(fd, 0, 0);

        while (len > 0)
        {
            int sublen = (int) Math.min(Integer.MAX_VALUE, len);
            trySkipCache(fd, offset, sublen);
            len -= sublen;
            offset -= sublen;
        }
    }

    public static void trySkipCache(int fd, long offset, int len)
    {
        if (fd < 0)
            return;

        try
        {
            if (System.getProperty("os.name").toLowerCase().contains("linux"))
            {
                posix_fadvise(fd, offset, len, POSIX_FADV_DONTNEED);
            }
        }
        catch (UnsatisfiedLinkError e)
        {
            // if JNA is unavailable just skipping Direct I/O
            // instance of this class will act like normal RandomAccessFile
        }
        catch (RuntimeException e)
        {
            if (!(e instanceof LastErrorException))
                throw e;

            logger.warn(String.format("posix_fadvise(%d, %d) failed, errno (%d).", fd, offset, errno(e)));
        }
    }

    public static int tryFcntl(int fd, int command, int flags)
    {
        // fcntl return value may or may not be useful, depending on the command
        int result = -1;

        try
        {
            result = fcntl(fd, command, flags);
        }
        catch (UnsatisfiedLinkError e)
        {
            // if JNA is unavailable just skipping
        }
        catch (RuntimeException e)
        {
            if (!(e instanceof LastErrorException))
                throw e;

            logger.warn(String.format("fcntl(%d, %d, %d) failed, errno (%d).", fd, command, flags, errno(e)));
        }

        return result;
    }

    public static int tryOpenDirectory(String path)
    {
        int fd = -1;

        try
        {
            return open(path, O_RDONLY);
        }
        catch (UnsatisfiedLinkError e)
        {
            // JNA is unavailable just skipping Direct I/O
        }
        catch (RuntimeException e)
        {
            if (!(e instanceof LastErrorException))
                throw e;

            logger.warn(String.format("open(%s, O_RDONLY) failed, errno (%d).", path, errno(e)));
        }

        return fd;
    }

    public static void trySync(int fd)
    {
        if (fd == -1)
            return;

        try
        {
            fsync(fd);
        }
        catch (UnsatisfiedLinkError e)
        {
            // JNA is unavailable just skipping Direct I/O
        }
        catch (RuntimeException e)
        {
            if (!(e instanceof LastErrorException))
                throw e;

            logger.warn(String.format("fsync(%d) failed, errno (%d).", fd, errno(e)));
        }
    }

    public static void tryCloseFD(int fd)
    {
        if (fd == -1)
            return;

        try
        {
            close(fd);
        }
        catch (UnsatisfiedLinkError e)
        {
            // JNA is unavailable just skipping Direct I/O
        }
        catch (RuntimeException e)
        {
            if (!(e instanceof LastErrorException))
                throw e;

            logger.warn(String.format("close(%d) failed, errno (%d).", fd, errno(e)));
        }
    }

    public static int getfd(FileChannel channel)
    {
        Field field = FBUtilities.getProtectedField(channel.getClass(), "fd");

        try
        {
            return getfd((FileDescriptor)field.get(channel));
        }
        catch (IllegalArgumentException|IllegalAccessException e)
        {
            logger.warn("Unable to read fd field from FileChannel");
        }
        return -1;
    }

    /**
     * Get system file descriptor from FileDescriptor object.
     * @param descriptor - FileDescriptor objec to get fd from
     * @return file descriptor, -1 or error
     */
    public static int getfd(FileDescriptor descriptor)
    {
        Field field = FBUtilities.getProtectedField(descriptor.getClass(), "fd");

        try
        {
            return field.getInt(descriptor);
        }
        catch (Exception e)
        {
            JVMStabilityInspector.inspectThrowable(e);
            logger.warn("Unable to read fd field from FileDescriptor");
        }

        return -1;
    }

    public static int getfd(String path)
    {
        RandomAccessFile file = null;
        try
        {
            file = new RandomAccessFile(path, "r");
            return getfd(file.getFD());
        }
        catch (Throwable t)
        {
            JVMStabilityInspector.inspectThrowable(t);
            // ignore
            return -1;
        }
        finally
        {
            try
            {
                if (file != null)
                    file.close();
            }
            catch (Throwable t)
            {
                // ignore
            }
        }
    }
}


text:
<?php

namespace GestionProjetBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * Mail
 *
 * @ORM\Table(name="mail")
 * @ORM\Entity(repositoryClass="GestionProjetBundle\Repository\MailRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Mail
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="bigint", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="\UserBundle\Entity\Utilisateur")
     */
    private $emetteur ;

	/**
     * @var \UserBundle\Entity\Utilisateur
     *
     * @ORM\ManyToOne(targetEntity="\UserBundle\Entity\Utilisateur")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="destinataire", referencedColumnName="id", nullable=true)
     * })
     */
    private $destinataire;

    /**
     * @var string
     *
     * @ORM\Column(name="objet", type="string", length=255, nullable=true)
     */
    private $objet;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="datetime", nullable=true)
     */
    private $date;

    /**
     * @var string
     *
     * @ORM\Column(name="contenu", type="text", nullable=true)
     */
    private $contenu;

    /**
     * @var integer
     *
     * @ORM\Column(name="type", type="integer", nullable=true)
     */
    private $type;

    /**
     * @var integer
     *
     * @ORM\Column(name="statut", type="integer", nullable=true)
     */
    private $statut;

    /**
     * @var \Doctrine\Common\Collections\Collection
     *
     * @ORM\ManyToMany(targetEntity="\UserBundle\Entity\Utilisateur", inversedBy="mails")
     * @ORM\JoinTable(name="mail_utilisateur",
     *   joinColumns={
     *     @ORM\JoinColumn(name="idMail", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="id", referencedColumnName="id")
     *   }
     * )
     */
    private $utilisateurs;

	/**
     * @ORM\Column(type="string", length=255, nullable=true)
    */
    private $path;

    /**
     * @Assert\File(maxSize="6000000")
    */
    private $file;

    private $temp;

    /**
    * @ORM\Column(type="array", nullable=true)
    */
    private $piecesjointes;

    /**
    * @ORM\Column(type="array", nullable=true)
    */
    private $originalpiecesjointes;

	/**
    * @var array
    */
    private $uploadedFiles;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->utilisateurs = new \Doctrine\Common\Collections\ArrayCollection();
		$this->piecesjointes = array();
        $this->originalpiecesjointes = array();
        $this->date = new \Datetime();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set objet
     *
     * @param string $objet
     * @return Mail
     */
    public function setObjet($objet)
    {
        $this->objet = $objet;

        return $this;
    }

    /**
     * Get objet
     *
     * @return string
     */
    public function getObjet()
    {
        return $this->objet;
    }

    /**
     * Set date
     *
     * @param \DateTime $date
     * @return Mail
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \DateTime
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * Set contenu
     *
     * @param string $contenu
     * @return Mail
     */
    public function setContenu($contenu)
    {
        $this->contenu = $contenu;

        return $this;
    }

    /**
     * Get contenu
     *
     * @return string
     */
    public function getContenu()
    {
        return $this->contenu;
    }

    /**
     * Set type
     *
     * @param integer $type
     * @return Mail
     */
    public function setType($type)
    {
        $this->type = $type;

        return $this;
    }

    /**
     * Get type
     *
     * @return integer
     */
    public function getType()
    {
        return $this->type;
    }

    /**
     * Set statut
     *
     * @param integer $statut
     * @return Mail
     */
    public function setStatut($statut)
    {
        $this->statut = $statut;

        return $this;
    }

    /**
     * Get statut
     *
     * @return integer
     */
    public function getStatut()
    {
        return $this->statut;
    }

    /**
     * Add utilisateur
     *
     * @param \UserBundle\Entity\Utilisateur $utilisateur
     * @return Mail
     */
    public function addUtilisateur(\UserBundle\Entity\Utilisateur $utilisateur)
    {
        $this->utilisateurs[] = $utilisateur;

        return $this;
    }

    /**
     * Remove utilisateur
     *
     * @param \UserBundle\Entity\Utilisateur $utilisateur
     */
    public function removeUtilisateur(\UserBundle\Entity\Utilisateur $utilisateur)
    {
        $this->utilisateurs->removeElement($utilisateur);
    }

    /**
     * Get utilisateur
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUtilisateurs()
    {
        return $this->utilisateurs;
    }

    /**
     * Set utilisateurs
     *
     * @param \Doctrine\Common\Collections\Collection $utilisateurs
     * @return Mail
     */
    public function setUtilisateurs(\Doctrine\Common\Collections\Collection $utilisateurs = null)
    {
        $this->utilisateurs = $utilisateurs;

        return $this;
    }

    /**
     * Set emetteur
     *
     * @param \UserBundle\Entity\Utilisateur $emetteur
     * @return Mail
     */
    public function setEmetteur(\UserBundle\Entity\Utilisateur $emetteur = null)
    {
        $this->emetteur = $emetteur;

        return $this;
    }

    /**
     * Get emetteur
     *
     * @return \UserBundle\Entity\Utilisateur
     */
    public function getEmetteur()
    {
        return $this->emetteur;
    }

	/**
     * Set destinataire
     *
     * @param \UserBundle\Entity\Utilisateur $destinataire
     * @return Mail
     */
    public function setDestinataire(\UserBundle\Entity\Utilisateur $destinataire = null)
    {
        $this->destinataire = $destinataire;

        return $this;
    }

    /**
     * Get destinataire
     *
     * @return \UserBundle\Entity\Utilisateur
     */
    public function getDestinataire()
    {
        return $this->destinataire;
    }

	/**
     * Set path
     *
     * @param string $path
     * @return Ressource
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * Get path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Set piecesjointes
     *
     * @param string $piecesjointes
     * @return Ressource
     */
    public function setPiecesjointes($piecesjointes)
    {
        $this->piecesjointes = $piecesjointes;

        return $this;
    }

    /**
     * Get piecesjointes
     *
     * @return array
     */
    public function getPiecesjointes()
    {
        return $this->piecesjointes;
    }

    /**
     * Set originalpiecesjointes
     *
     * @param string $originalpiecesjointes
     * @return Ressource
     */
    public function setOriginalpiecesjointes($originalpiecesjointes)
    {
        $this->originalpiecesjointes = $originalpiecesjointes;

        return $this;
    }

    /**
     * Get originalpiecesjointes
     *
     * @return array
     */
    public function getOriginalpiecesjointes()
    {
        return $this->originalpiecesjointes;
    }

    /**
     * @param UploadedFile $file
     * @return object
     */
    public function setFile(UploadedFile $file = null) {
        $this->file = $file;
        // check if we have an old image path
        if (isset($this->path)) {
            // store the old name to delete after the update
            $this->temp = $this->path;
            $this->path = null;
        } else {
            $this->path = 'initial';
        }
    }

    /**
     * Get the file used for profile picture uploads
     *
     * @return UploadedFile
     */
    public function getFile() {

        return $this->file;
    }

     protected function getUploadRootDir() {
        return __DIR__ . '/../../../web/uploads/couriers';
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload() {
        if (null !== $this->getFile()) {
            // do whatever you want to generate a unique name
            $filename = sha1(uniqid(mt_rand(), true));
            $this->path = $filename . '.' . $this->getFile()->guessExtension();
        }
    }

    /**
     * Generates a 32 char long random filename
     *
     * @return string
     */
    public function generateRandomProfilePictureFilename() {
        $count = 0;
        do {
            $generator = new SecureRandom();
            $random = $generator->nextBytes(16);
            $randomString = bin2hex($random);
            $count++;
        } while (file_exists($this->getUploadRootDir() . '/' . $randomString . '.' . $this->getFile()->guessExtension()) && $count < 50);

        return $randomString;
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload() {
        if (null === $this->getFile()) {
            return;
        }

        // if there is an error when moving the file, an exception will
        // be automatically thrown by move(). This will properly prevent
        // the entity from being persisted to the database on error
        $this->getFile()->move($this->getUploadRootDir(), $this->path);
        $info = pathinfo($this->getFile()->getClientOriginalName());
        $file_name =  basename($this->getFile()->getClientOriginalName(),'.'.$info['extension']);
        $this->setReference($file_name);
        // check if we have an old image
        if (isset($this->temp)) {
            // delete the old image
            //unlink($this->getUploadRootDir().'/'.$this->temp);
            //ou je renomme
            rename($this->getUploadRootDir() . '/' . $this->temp, $this->getUploadRootDir() . '/old' . $this->temp);
            // clear the temp image path
            $this->temp = null;
        }
        $this->file = null;
    }

    /**
     * Sets uploadedFiles.
     *
     * @param array $uploadedFiles
     */
    public function setUploadedFiles(array $uploadedFiles = null)
    {
        $this->uploadedFiles = $uploadedFiles;
    }

    /**
     * Get uploadedFiles.
     *
     * @return array
     */
    public function getUploadedFiles()
    {
        return $this->uploadedFiles;
    }

    /**
    * @ORM\PreFlush()
    */
    public function uploadPiecesjointes()
    {
        if($this->uploadedFiles){
            $this->piecesjointes= array();
            $this->originalpiecesjointes= array();
            foreach($this->uploadedFiles as $file)
            {
                $info = pathinfo($file->getClientOriginalName());
                $file_name =  basename($file->getClientOriginalName(),'.'.$info['extension']);
                array_push($this->originalpiecesjointes, $file_name);
                $path = sha1(uniqid(mt_rand(), true)).'.'.$file->guessExtension();
                array_push ($this->piecesjointes, $path);
                $file->move($this->getUploadRootDir(), $path);
                unset($file);
            }
        }

        $this->uploadedFiles=array();
    }

}


text:
======
从功能需求、设计模式、最佳实践出发考虑

##MVP模式
数据、显示、控制解耦,[mosby](https://github.com/sockeqwe/mosby),作者[blog1](http://hannesdorfmann.com/android/mosby/),[blog2](http://hannesdorfmann.com/android/mosby-playbook/)

##依赖注入
+  普通数据注入,[Dagger](http://google.github.io/dagger/)
+  View注入[ButterKnife](http://jakewharton.github.io/butterknife/)。

##数据存储
+  ~~[squidb](https://github.com/yahoo/squidb),基于注解,编译期生成DAO类,model类是编译期生成的,而不是定义表结构的类,对复杂SQL语句的支持非常好~~
+  [DBFlow](https://github.com/Raizlabs/DBFlow),基于注解,编译期生成DAO类,对关系的支持很好
+  ~~[ActiveAndroid](https://github.com/pardom/ActiveAndroid),基于注解,运行时转换~~
+  ~~[greenDAO](https://github.com/greenrobot/greenDAO),编译期生成辅助代码~~
+  [StorIO](https://github.com/pushtorefresh/storio),与rx集成,响应式DBHelper框架

##网络连接处理
+  [Retrofit](http://square.github.io/retrofit/),使用动态代理将java接口转化为REST API
+  [OkHttp](http://square.github.io/okhttp/),优化的HTTP client(共享连接,连接池,透明压缩,缓存,重试等),支持web socket协议

##异步处理
+  响应式编程([rx](https://github.com/ReactiveX/RxAndroid),在java7中使用lambda语法:[retrolambda](https://github.com/orfjackal/retrolambda)),消息的发出者和响应的接收者在同一模块内,局部性、单对单
+  事件处理([EventBus](https://github.com/greenrobot/EventBus),~~[Otto](http://square.github.io/otto/)~~),全局性事件、一对多比较合适

##测试
+  单元测试([我的印象笔记](https://www.evernote.com/shard/s425/sh/ed5e5a9b-8ebf-4d72-8d4d-62bff3b57335/a172972c726caab6),[Robolectric](http://robolectric.org/),使得Android代码能够在PC的JVM上运行测试,加快速度)
  +  对rx的单元测试,[非官方RxAssertions](https://gist.github.com/ivacf/874dcb476bfc97f4d555),[官方TestSubscriber](http://reactivex.io/RxJava/javadoc/rx/observers/TestSubscriber.html)
  +  [AndroidTDD](AndroidTDD.md)
+  集成测试([我的印象笔记](https://www.evernote.com/shard/s425/sh/52ec6ce5-68ca-47d7-8fa1-14fdacfc3f1a/31fceed7211d8e13),[Espresso](https://code.google.com/p/android-test-kit/wiki/Espresso))

##持续集成
+  [jenkins-ci](http://jenkins-ci.org/),整合代码托管工具,commit、merge request自动触发构建

##工具
+  图片加载
  +  [Fresco](https://github.com/facebook/fresco),多来源加载、缓存、内存管理(存放在安卓非堆特殊内存区域)、支持多种格式、多种功能(圆角)
  +  [Glide](https://github.com/bumptech/glide),多来源加载、缓存、Object pool内存优化、Context生命周期加载优化、ListView、RecyclerView等加载优化
  +  ~~[Picasso](http://square.github.io/picasso/),使用堆内存,格式稍少~~
+  模块热加载
  +  [dynamic-load-apk](https://github.com/singwhatiwanna/dynamic-load-apk),通过代理实现启动、显示、执行安装时未定义的Activity,Service,实现模块热加载
+  错误统计
  +  [fabric](https://get.fabric.io/),提供crash统计、以及twitter集成
+  调试
  +  [XLog](https://github.com/promeG/XLog),函数调用追踪,log出参数、返回值、线程、执行时间,支持方法、类的注解;
  +  [Fresco](https://github.com/facebook/fresco),chrome查看log,view heriachy,shared pref,db等;
  +  [LeakCanary](https://github.com/square/leakcanary),memory leak检测工具;
+  时间
  +  [ThreeTenBP](https://github.com/ThreeTen/threetenbp),JSR310的java 8以前的兼容实现,比安卓的Date类等强大无数倍;
  +  [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP),安卓的一个包装,init过程性能更好;
+  导航
  +  [FragmentArgs](https://github.com/sockeqwe/fragmentargs),Fragment启动时通过Argument传递参数
  +  [Dart](https://github.com/f2prateek/dart),Activity之间通过Intent传递Extra参数
  +  [Pocket Knife](https://github.com/hansenji/pocketknife),Activity的Extra传递参数,SavedInstance做状态保存/恢复
  +  [Aftermath](https://github.com/MichaelEvans/Aftermath),A simple, annotation-based Android library for generating onActivityForResult handlers.
+  动效
  +  [rebound](https://github.com/facebook/rebound),通过Android系统的property transition,加上各种变换函数,实现模拟物理的动效;
+  设计
  +  sketch
  +  [zeplin](https://zeplin.io/)

# Develop maintainable apps
+  Libraries
选择第三方库时的考虑
  +  Documentation: 文档是否全面
  +  Repository Check-ins(Stability): 稳定性、是否保持维护
  +  Fulfils a Need: 满足项目需求
+  Domain design
  +  Keep code simple: OO,一个类只负责一件事
  +  Use MVC/MVP/MVVM Pattern
  +  Functional Test
  +  Use the tools: IDE的重构工具很强大
+  Code quality
  +  Readability matters
  +  工具
    +  CheckStyle
    +  Lint
    +  Findbugs
    +  PMD
  +  Refactor Gradually
+  Testing
  +  Unit test: Every single line of code that you write should be tested. Peroid. -- Robert Martin
  +  Junit(...) + Mockito
  +  Continuous Integration
  +  Code coverage

# [Android Clean Architecture](https://github.com/android10/Android-CleanArchitecture)
======
##分层结构
![clean_architecture1.png](assets/clean_architecture1.png)
+  Entities: These are the business objects of the application.
+  Use Cases: These use cases orchestrate the flow of data to and from the entities. Are also called Interactors.
+  Interface Adapters: This set of adapters convert data from the format most convenient for the use cases and entities. Presenters and Controllers belong here.
+  Frameworks and Drivers: This is where all the details go: UI, tools, frameworks, etc.
+  Dependency Rule: source code dependencies can only point inwards and nothing in an inner circle can know anything at all about something in an outer circle.

##安卓项目层次结构示例
![clean_architecture_android.png](assets/clean_architecture_android.png)

##使用Rx后的层次结构示例
![clean_architecture_evolution.png](assets/clean_architecture_evolution.png)
+  Presentation layer: UI tests with Espresso 2 and Android Instrumentation.
+  Presenter && View test: 针对接口进行单元测试;对UI简单交互结果逻辑的测试(如:Activity跳转,Fragment切换,相关接口调用);
+  Domain layer: JUnit + Mockito since it is a regular Java module.
+  Data layer: Migrated test battery to use Robolectric 3 + JUnit + Mockito.

##代码组织(包组织)
+  Package by layer
+  Package by feature
  +  Higher Modularity
  +  Easier Code Navigation
  +  Minimizes Scope

#[Flux Architecture](http://lgvalle.github.io/2015/08/04/flux-architecture/)
======
+  结构图
![flux-graph-simple.png](assets/flux-graph-simple.png)
  +  View: Application interface. It create actions in response to user interactions. Activity or Fragment
  +  Dispatcher: Central hub through which pass all actions and whose responsibility is to make them arrive to every Store. An event bus.
  +  Store: Maintain the state for a particular application domain. They respond to actions according to current state, execute business logic and emit a change event when they are done. This event is used by the view to update its interface. Simple POJOs with two main attributes: Type: a String identifying the type of event; Data: a Map with the payload for this action.
  +  More about Stores
    +  Stores contain the status of the application and its business logic.
    +  Stores react to Actions emitted by the Dispatcher, execute business logic and emit a change event as result.
    +  ...