text:
title: dateFormat
description: Converts the textual representation of the `datetime` into the specified format.
godocref: https://golang.org/pkg/time/
date: 2017-02-01
publishdate: 2017-02-01
lastmod: 2017-02-01
categories: [functions]
menu:
  docs:
    parent: "functions"
keywords: [dates,time,strings]
signature: ["dateFormat LAYOUT INPUT"]
workson: []
hugoversion:
relatedfuncs: [Format,now,Unix,time]
deprecated: false
---

`dateFormat` converts the textual representation of the `datetime` into the specified format or returns it as a Go `time.Time` type value. These are formatted with the layout string.

```
{{ dateFormat "Monday, Jan 2, 2006" "2015-01-21" }} → "Wednesday, Jan 21, 2015"
```

{{% warning %}}
As of v0.19 of Hugo, the `dateFormat` function is *not* supported as part of Hugo's [multilingual feature](/content-management/multilingual/).
{{% /warning %}}

See the [`Format` function](/functions/format/) for a more complete list of date formatting options in your templates.


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

namespace DrdPlus\Tests\Tables\Measurements\Amount;

use DrdPlus\Tests\Tables\Measurements\AbstractTestOfBonus;

class AmountBonusTest extends AbstractTestOfBonus
{

}

redpajama_set_name: RedPajamaGithub


text:
========================
ini "copas" untuk CONTOH
========================
============================================================================
source : http://www.script-tutorials.com/how-to-parse-web-pages-using-xpath/
============================================================================

<?php
$sUrl = 'http://news.google.com/news/section?pz=1&cf=all&topic=t&ict=ln';
$sUrlSrc = getWebsiteContent($sUrl);

// Load the source
$dom = new DOMDocument();
@$dom->loadHTML($sUrlSrc);

$xpath = new DomXPath($dom);

// all links contain 'iPhone':
$aLinks = array();
$vRes = $xpath->query(".//*[@id='top-stories']/div/h2/a[1]/span[contains(text(),'iPhone')]");
foreach ($vRes as $obj) {
    $aLinks[$obj->nodeValue] = $obj->parentNode->getAttribute('href');
}

// all links from 5 to 10
$aLinks2 = array();
$vRes = $xpath->query(".//*[@id='top-stories']/div[position() > 5][position() < 10]/h2/a[1]/span");
foreach ($vRes as $obj) {
    $aLinks2[$obj->nodeValue] = $obj->parentNode->getAttribute('href');
}

echo '<link href="css/styles.css" type="text/css" rel="stylesheet"/>
';
echo '
Using xpath for dom html (2)
';

echo '
All links contain "iPhone" word
';
foreach ($aLinks as $sTitle => $sLink) {
    echo <<<EOF

    {$sTitle}

EOF;
}
echo '

Links from 5 to 10
';
foreach ($aLinks2 as $sTitle => $sLink) {
    echo <<<EOF

    {$sTitle}

EOF;
}
echo '
';

// this function will return page content using caches (we will load original sources not more than once per hour)
function getWebsiteContent($sUrl) {
    // our folder with cache files
    $sCacheFolder = 'cache/';

    // cache filename
    $sFilename = date('YmdH').'.html';

    if (! file_exists($sCacheFolder.$sFilename)) {
        $ch = curl_init($sUrl);
        $fp = fopen($sCacheFolder.$sFilename, 'w');
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, Array('User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.15) Gecko/20080623 Firefox/2.0.0.15'));
        curl_exec($ch);
        curl_close($ch);
        fclose($fp);
    }
    return file_get_contents($sCacheFolder.$sFilename);
}

?>


text:
package com.esf.web;

import java.io.IOException;
import javax.servlet.http.*;

@SuppressWarnings("serial")
public class EsfwebServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.getWriter().println("Hello, world");
	}
}


text:
using System;

namespace _02.ChooseADrink2._0
{
    class Program
    {
        static void Main(string[] args)
        {
            string profession = Console.ReadLine();
            int quantity = int.Parse(Console.ReadLine());
            double coffeePrice = 1.0;
            double waterPrice = 0.7;
            double beerPrice = 1.70;
            double teaPrice = 1.20;
            double totalPrice = 0.0;

            if (profession == "Athlete")
            {
                totalPrice = waterPrice * quantity;
            }
            else if (profession == "Businessman" || profession == "Businesswoman")
            {
                totalPrice = coffeePrice * quantity;
            }
            else if (profession == "SoftUni Student")
            {
                totalPrice = beerPrice * quantity;
            }
            else
            {
                totalPrice = teaPrice * quantity;
            }
            Console.WriteLine($"The {profession} has to pay {totalPrice:F2}.");
        }
    }
}


text:
package org.deeplearning4j.models.glove.count;

import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement;

/**
 * Created by raver on 24.12.2015.
 */
public interface CoOccurenceReader<T extends SequenceElement> {
    /*
        Storage->Memory merging part
     */
    boolean hasMoreObjects();

    CoOccurrenceWeight<T> nextObject();

    void finish();
}


text:
module Feather
  class PingLog
    include DataMapper::Resource

    property :id, Integer, :serial => true
    property :ping_service_id, Integer
    property :message, String, :nullable => false, :length => 255
    property :successful, Boolean
    property :created_at, DateTime

    validates_present :message, :key => "uniq_ping_log_message"

    def service
      @ping_service ||= Feather::PingService[self.ping_service_id]
    end
  end
end


text:
.order-img img {
  height: 5em;
  width: auto;
}

.card .order-img {
  float: left;
  padding-bottom: 0px;
}

.current-prototype, .history-prototype {
  display: none;
}

#listings_stillUp .card a {
  position: absolute;
  width: 100%;
  height: 100%;
}

#header button {
  float: right;
}


text:
namespace Appccelerate.StateMachine
{
    /// <summary>
    /// Tests the <see cref="ActiveStateMachine{TState,TEvent}"/> class.
    /// </summary>
    public class ActiveStateMachineTest : StateMachineTestBase<ActiveStateMachine<States, Events>>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="ActiveStateMachineTest"/> class.
        /// </summary>
        public ActiveStateMachineTest()
            : base(new ActiveStateMachine<States, Events>("Test Machine"))
        {
        }
    }
}


text:
//
//  HLSTask.h
//  CoconutKit
//
//  Created by Samuel Défago on 12/17/10.
//  Copyright 2010 Hortis. All rights reserved.
//

// Forward declarations
@class HLSTaskGroup;
@protocol HLSTaskDelegate;

#define kTaskNoTimeIntervalEstimateAvailable        -1.

/**
 * Abstract class for tasks. Tasks offer a delegate mechanism for tracking their status. To create your own
 * tasks, simply subclass HLSTask and override the -operationClass method to return the class of the operation
 * responsible for processing the task.
 *
 * A task must not be submitted several times simultaneously (this leads to undefined behavior). A task
 * which was fully processed can be submitted again (and with another delegate if needed), but only when it
 * is not running anymore.
 *
 * Designated initializer: -init
 */
@interface HLSTask : NSObject {
@private
    NSString *_tag;
    NSDictionary *_userInfo;
    BOOL _running;
    BOOL _finished;
    BOOL _cancelled;
    float _progress;
    NSTimeInterval _remainingTimeIntervalEstimate;
    NSDate *_lastEstimateDate;              // date & time when the remaining time was previously estimated ...
    float _lastEstimateProgress;            // ... and corresponding progress value
    NSUInteger _progressStepsCounter;
    NSDictionary *_returnInfo;
    NSError *_error;
    HLSTaskGroup *_taskGroup;               // parent task group if any, nil if none
}

/**
 * Class responsible of processing the task. Must be a subclass of HLSTaskOperation
 * Must be overridden
 */
- (Class)operationClass;

/**
 * Optional tag to identify a task
 * Not meant to be overridden
 */
@property (nonatomic, retain) NSString *tag;

/**
 * Dictionary which can be used freely to convey additional information
 * Not meant to be overridden
 */
@property (nonatomic, retain) NSDictionary *userInfo;

/**
 * Return YES if the task processing is running
 * Not meant to be overridden
 */
@property (nonatomic, readonly, assign, getter=isRunning) BOOL running;

/**
 * Return YES if the task processing is over (this can be because the operation has completed its task,
 * or after it has been cancelled)
 */
@property (nonatomic, readonly, assign, getter=isFinished) BOOL finished;

/**
 * Return YES if the task group has been cancelled
 */
@property (nonatomic, readonly, assign, getter=isCancelled) BOOL cancelled;

/**
 * Task progress value (always between 0.f and 1.f). A task might not reach 1.f if it fails
 * Not meant to be overridden
 */
@property (nonatomic, readonly, assign) float progress;

/**
 * Return an estimate about the remaining time before the task processing completes (or kTaskNoTimeIntervalEstimateAvailable if no
 * estimate is available yet)
 * Important remark: Accurate measurements can only be obtained if the progress update rate of a task is not varying fast (in another
 *                   words: constant over long enough periods of time). This is for example usually the case for download or
 *                   inflating / deflating tasks.
 * Not meant to be overridden
 */
@property (nonatomic, readonly, assign) NSTimeInterval remainingTimeIntervalEstimate;

/**
 * Return a localized string describing the estimated time before completion
 * (see remark of -remainingTimeIntervalEstimate method)
 * Not meant to be overridden
 */
- (NSString *)remainingTimeIntervalEstimateLocalizedString;

/**
 * NSDictionary which can freely be used to convey return information
 * Not meant to be overridden
 */
@property (nonatomic, readonly, retain) NSDictionary *returnInfo;

/**
 * When the process is complete, check this property to find out if an error was encountered
 * Not meant to be overridden
 */
@property (nonatomic, readonly, retain) NSError *error;

@end

@protocol HLSTaskDelegate <NSObject>
@optional

/**
 * The task has started processing
 */
- (void)taskHasStartedProcessing:(HLSTask *)task;

/**
 * The task is being processed and has an updated status (you can call progress to get its completion
 * status)
 */
- (void)taskProgressUpdated:(HLSTask *)task;

/**
 * The task has been fully processed. Check the error property to find if the processing was successful or not (and
 * why)
 */
- (void)taskHasBeenProcessed:(HLSTask *)task;

/**
 * The task has been cancelled
 */
- (void)taskHasBeenCancelled:(HLSTask *)task;

@end


text:
$FireFoxBasePolicyRegKey = 'HKLM:\Software\Policies\Mozilla\Firefox'

ForceRegKey($FireFoxBasePolicyRegKey)


text:
<?php
class Kwc_Newsletter_QueueRow extends Kwf_Model_Proxy_Row
{
    public function getRecipient()
    {
        $modelname = $this->recipient_model;
        if (is_instance_of($modelname, 'Kwf_Model_Abstract')) {
            $row = Kwf_Model_Abstract::getInstance($modelname)->getRow($this->recipient_id);
        } else if (is_instance_of($modelname, 'Zend_Db_Table_Abstract')) {
            $row = Kwf_Dao::getTable($modelname)->find($this->recipient_id)->current();
        } else {
            throw new Kwf_Exception("Recipient-Model for id {$this->id} has to be a model or a table.");
        }
        if ($row && !$row instanceof Kwc_Mail_Recipient_Interface) {
            throw new Kwf_Exception("Recipient-Row has to implement Kwc_Mail_Recipient_Interface");
        }
        return $row;
    }
}


text:
package main_test

import (
	"encoding/json"
	"os"
	"runtime"

	"code.cloudfoundry.org/diego-ssh/keys"
	"code.cloudfoundry.org/inigo/helpers/portauthority"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"

	"testing"
)

var (
	sshdPath string

	sshdPort            uint16
	hostKeyPem          string
	privateKeyPem       string
	publicAuthorizedKey string

	portAllocator portauthority.PortAllocator
)

func TestSSHDaemon(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Sshd Suite")
}

var _ = SynchronizedBeforeSuite(func() []byte {
	if runtime.GOOS == "windows" {
		if os.Getenv("WINPTY_DLL_DIR") == "" {
			Fail("Missing WINPTY_DLL_DIR environment variable")
		}
	}
	sshd := buildSshd()

	hostKey, err := keys.RSAKeyPairFactory.NewKeyPair(1024)
	Expect(err).NotTo(HaveOccurred())

	privateKey, err := keys.RSAKeyPairFactory.NewKeyPair(1024)
	Expect(err).NotTo(HaveOccurred())

	payload, err := json.Marshal(map[string]string{
		"sshd":           sshd,
		"host-key":       hostKey.PEMEncodedPrivateKey(),
		"private-key":    privateKey.PEMEncodedPrivateKey(),
		"authorized-key": privateKey.AuthorizedKey(),
	})

	Expect(err).NotTo(HaveOccurred())

	return payload
}, func(payload []byte) {
	context := map[string]string{}

	err := json.Unmarshal(payload, &context)
	Expect(err).NotTo(HaveOccurred())

	hostKeyPem = context["host-key"]
	privateKeyPem = context["private-key"]
	publicAuthorizedKey = context["authorized-key"]

	node := GinkgoParallelProcess()
	startPort := 1050 * node
	portRange := 1000
	endPort := startPort + portRange

	portAllocator, err = portauthority.New(startPort, endPort)
	Expect(err).NotTo(HaveOccurred())

	sshdPort, err = portAllocator.ClaimPorts(1)
	Expect(err).NotTo(HaveOccurred())

	sshdPath = context["sshd"]
})

var _ = SynchronizedAfterSuite(func() {
}, func() {
	gexec.CleanupBuildArtifacts()
})


text:
import * as json from 'vs/base/common/json';
import { ResourceMap } from 'vs/base/common/map';
import * as arrays from 'vs/base/common/arrays';
import * as types from 'vs/base/common/types';
import * as objects from 'vs/base/common/objects';
import { URI } from 'vs/base/common/uri';
import { OVERRIDE_PROPERTY_PATTERN } from 'vs/platform/configuration/common/configurationRegistry';
import { IOverrides, overrideIdentifierFromKey, addToValueTree, toValuesTree, IConfigurationModel, getConfigurationValue, IConfigurationOverrides, IConfigurationData, getDefaultValues, getConfigurationKeys, IConfigurationChangeEvent, ConfigurationTarget, removeFromValueTree, toOverrides } from 'vs/platform/configuration/common/configuration';
import { Workspace } from 'vs/platform/workspace/common/workspace';

export class ConfigurationModel implements IConfigurationModel {

	private isFrozen: boolean = false;

	constructor(
		private _contents: any = {},
		private _keys: string[] = [],
		private _overrides: IOverrides[] = []
	) {
	}

	get contents(): any {
		return this.checkAndFreeze(this._contents);
	}

	get overrides(): IOverrides[] {
		return this.checkAndFreeze(this._overrides);
	}

	get keys(): string[] {
		return this.checkAndFreeze(this._keys);
	}

	getValue<V>(section: string): V {
		return section ? getConfigurationValue<any>(this.contents, section) : this.contents;
	}

	override(identifier: string): ConfigurationModel {
		const overrideContents = this.getContentsForOverrideIdentifer(identifier);

		if (!overrideContents || typeof overrideContents !== 'object' || !Object.keys(overrideContents).length) {
			// If there are no valid overrides, return self
			return this;
		}

		let contents = {};
		for (const key of arrays.distinct([...Object.keys(this.contents), ...Object.keys(overrideContents)])) {

			let contentsForKey = this.contents[key];
			let overrideContentsForKey = overrideContents[key];

			// If there are override contents for the key, clone and merge otherwise use base contents
			if (overrideContentsForKey) {
				// Clone and merge only if base contents and override contents are of type object otherwise just override
				if (typeof contentsForKey === 'object' && typeof overrideContentsForKey === 'object') {
					contentsForKey = objects.deepClone(contentsForKey);
					this.mergeContents(contentsForKey, overrideContentsForKey);
				} else {
					contentsForKey = overrideContentsForKey;
				}
			}

			contents[key] = contentsForKey;
		}

		return new ConfigurationModel(contents);
	}

	merge(...others: ConfigurationModel[]): ConfigurationModel {
		const contents = objects.deepClone(this.contents);
		const overrides = objects.deepClone(this.overrides);
		const keys = [...this.keys];

		for (const other of others) {
			this.mergeContents(contents, other.contents);

			for (const otherOverride of other.overrides) {
				const [override] = overrides.filter(o => arrays.equals(o.identifiers, otherOverride.identifiers));
				if (override) {
					this.mergeContents(override.contents, otherOverride.contents);
				} else {
					overrides.push(objects.deepClone(otherOverride));
				}
			}
			for (const key of other.keys) {
				if (keys.indexOf(key) === -1) {
					keys.push(key);
				}
			}
		}
		return new ConfigurationModel(contents, keys, overrides);
	}

	freeze(): ConfigurationModel {
		this.isFrozen = true;
		return this;
	}

	private mergeContents(source: any, target: any): void {
		for (const key of Object.keys(target)) {
			if (key in source) {
				if (types.isObject(source[key]) && types.isObject(target[key])) {
					this.mergeContents(source[key], target[key]);
					continue;
				}
			}
			source[key] = objects.deepClone(target[key]);
		}
	}

	private checkAndFreeze<T>(data: T): T {
		if (this.isFrozen && !Object.isFrozen(data)) {
			return objects.deepFreeze(data);
		}
		return data;
	}

	private getContentsForOverrideIdentifer(identifier: string): any {
		for (const override of this.overrides) {
			if (override.identifiers.indexOf(identifier) !== -1) {
				return override.contents;
			}
		}
		return null;
	}

	toJSON(): IConfigurationModel {
		return {
			contents: this.contents,
			overrides: this.overrides,
			keys: this.keys
		};
	}

	// Update methods

	public setValue(key: string, value: any) {
		this.addKey(key);
		addToValueTree(this.contents, key, value, e => { throw new Error(e); });
	}

	public removeValue(key: string): void {
		if (this.removeKey(key)) {
			removeFromValueTree(this.contents, key);
		}
	}

	private addKey(key: string): void {
		let index = this.keys.length;
		for (let i = 0; i < index; i++) {
			if (key.indexOf(this.keys[i]) === 0) {
				index = i;
			}
		}
		this.keys.splice(index, 1, key);
	}

	private removeKey(key: string): boolean {
		let index = this.keys.indexOf(key);
		if (index !== -1) {
			this.keys.splice(index, 1);
			return true;
		}
		return false;
	}
}

export class DefaultConfigurationModel extends ConfigurationModel {

	constructor() {
		const contents = getDefaultValues();
		const keys = getConfigurationKeys();
		const overrides: IOverrides[] = [];
		for (const key of Object.keys(contents)) {
			if (OVERRIDE_PROPERTY_PATTERN.test(key)) {
				overrides.push({
					identifiers: [overrideIdentifierFromKey(key).trim()],
					contents: toValuesTree(contents[key], message => console.error(`Conflict in default settings file: ${message}`))
				});
			}
		}
		super(contents, keys, overrides);
	}
}

export class ConfigurationModelParser {

	private _configurationModel: ConfigurationModel | null = null;
	private _parseErrors: any[] = [];

	constructor(protected readonly _name: string) { }

	get configurationModel(): ConfigurationModel {
		return this._configurationModel || new ConfigurationModel();
	}

	get errors(): any[] {
		return this._parseErrors;
	}

	public parse(content: string): void {
		const raw = this.parseContent(content);
		const configurationModel = this.parseRaw(raw);
		this._configurationModel = new ConfigurationModel(configurationModel.contents, configurationModel.keys, configurationModel.overrides);
	}

	protected parseContent(content: string): any {
		let raw: any = {};
		let currentProperty: string | null = null;
		let currentParent: any = [];
		let previousParents: any[] = [];
		let parseErrors: json.ParseError[] = [];

		function onValue(value: any) {
			if (Array.isArray(currentParent)) {
				(<any[]>currentParent).push(value);
			} else if (currentProperty) {
				currentParent[currentProperty] = value;
			}
		}

		let visitor: json.JSONVisitor = {
			onObjectBegin: () => {
				let object = {};
				onValue(object);
				previousParents.push(currentParent);
				currentParent = object;
				currentProperty = null;
			},
			onObjectProperty: (name: string) => {
				currentProperty = name;
			},
			onObjectEnd: () => {
				currentParent = previousParents.pop();
			},
			onArrayBegin: () => {
				let array: any[] = [];
				onValue(array);
				previousParents.push(currentParent);
				currentParent = array;
				currentProperty = null;
			},
			onArrayEnd: () => {
				currentParent = previousParents.pop();
			},
			onLiteralValue: onValue,
			onError: (error: json.ParseErrorCode, offset: number, length: number) => {
				parseErrors.push({ error, offset, length });
			}
		};
		if (content) {
			try {
				json.visit(content, visitor);
				raw = currentParent[0] || {};
			} catch (e) {
				console.error(`Error while parsing settings file ${this._name}: ${e}`);
				this._parseErrors = [e];
			}
		}

		return raw;
	}

	protected parseRaw(raw: any): IConfigurationModel {
		const contents = toValuesTree(raw, message => console.error(`Conflict in settings file ${this._name}: ${message}`));
		const keys = Object.keys(raw);
		const overrides: IOverrides[] = toOverrides(raw, message => console.error(`Conflict in settings file ${this._name}: ${message}`));
		return { contents, keys, overrides };
	}
}

export class Configuration {

	private _workspaceConsolidatedConfiguration: ConfigurationModel | null = null;
	private _foldersConsolidatedConfigurations: ResourceMap<ConfigurationModel> = new ResourceMap<ConfigurationModel>();

	constructor(
		private _defaultConfiguration: ConfigurationModel,
		private _userConfiguration: ConfigurationModel,
		private _workspaceConfiguration: ConfigurationModel = new ConfigurationModel(),
		private _folderConfigurations: ResourceMap<ConfigurationModel> = new ResourceMap<ConfigurationModel>(),
		private _memoryConfiguration: ConfigurationModel = new ConfigurationModel(),
		private _memoryConfigurationByResource: ResourceMap<ConfigurationModel> = new ResourceMap<ConfigurationModel>(),
		private _freeze: boolean = true) {
	}

	getValue(section: string, overrides: IConfigurationOverrides, workspace: Workspace): any {
		const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace);
		return consolidateConfigurationModel.getValue(section);
	}

	updateValue(key: string, value: any, overrides: IConfigurationOverrides = {}): void {
		let memoryConfiguration: ConfigurationModel;
		if (overrides.resource) {
			memoryConfiguration = this._memoryConfigurationByResource.get(overrides.resource);
			if (!memoryConfiguration) {
				memoryConfiguration = new ConfigurationModel();
				this._memoryConfigurationByResource.set(overrides.resource, memoryConfiguration);
			}
		} else {
			memoryConfiguration = this._memoryConfiguration;
		}

		if (value === void 0) {
			memoryConfiguration.removeValue(key);
		} else {
			memoryConfiguration.setValue(key, value);
		}

		if (!overrides.resource) {
			this._workspaceConsolidatedConfiguration = null;
		}
	}

	inspect<C>(key: string, overrides: IConfigurationOverrides, workspace: Workspace): {
		default: C,
		user: C,
		workspace?: C,
		workspaceFolder?: C
		memory?: C
		value: C,
	} {
		const consolidateConfigurationModel = this.getConsolidateConfigurationModel(overrides, workspace);
		const folderConfigurationModel = this.getFolderConfigurationModelForResource(overrides.resource, workspace);
		const memoryConfigurationModel = overrides.resource ? this._memoryConfigurationByResource.get(overrides.resource) || this._memoryConfiguration : this._memoryConfiguration;
		return {
			default: overrides.overrideIdentifier ? this._defaultConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._defaultConfiguration.freeze().getValue(key),
			user: overrides.overrideIdentifier ? this._userConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._userConfiguration.freeze().getValue(key),
			workspace: workspace ? overrides.overrideIdentifier ? this._workspaceConfiguration.freeze().override(overrides.overrideIdentifier).getValue(key) : this._workspaceConfiguration.freeze().getValue(key) : void 0, //Check on workspace exists or not because _workspaceConfiguration is never null
			workspaceFolder: folderConfigurationModel ? overrides.overrideIdentifier ? folderConfigurationModel.freeze().override(overrides.overrideIdentifier).getValue(key) : folderConfigurationModel.freeze().getValue(key) : void 0,
			memory: overrides.overrideIdentifier ? memoryConfigurationModel.freeze().override(overrides.overrideIdentifier).getValue(key) : memoryConfigurationModel.freeze().getValue(key),
			value: consolidateConfigurationModel.getValue(key)
		};
	}

	keys(workspace: Workspace): {
		default: string[];
		user: string[];
		workspace: string[];
		workspaceFolder: string[];
	} {
		const folderConfigurationModel = this.getFolderConfigurationModelForResource(undefined, workspace);
		return {
			default: this._defaultConfiguration.freeze().keys,
			user: this._userConfiguration.freeze().keys,
			workspace: this._workspaceConfiguration.freeze().keys,
			workspaceFolder: folderConfigurationModel ? folderConfigurationModel.freeze().keys : []
		};
	}

	updateDefaultConfiguration(defaultConfiguration: ConfigurationModel): void {
		this._defaultConfiguration = defaultConfiguration;
		this._workspaceConsolidatedConfiguration = null;
		this._foldersConsolidatedConfigurations.clear();
	}

	updateUserConfiguration(userConfiguration: ConfigurationModel): void {
		this._userConfiguration = userConfiguration;
		this._workspaceConsolidatedConfiguration = null;
		this._foldersConsolidatedConfigurations.clear();
	}

	updateWorkspaceConfiguration(workspaceConfiguration: ConfigurationModel): void {
		this._workspaceConfiguration = workspaceConfiguration;
		this._workspaceConsolidatedConfiguration = null;
		this._foldersConsolidatedConfigurations.clear();
	}

	updateFolderConfiguration(resource: URI, configuration: ConfigurationModel): void {
		this._folderConfigurations.set(resource, configuration);
		this._foldersConsolidatedConfigurations.delete(resource);
	}

	deleteFolderConfiguration(resource: URI): void {
		this.folders.delete(resource);
		this._foldersConsolidatedConfigurations.delete(resource);
	}

	get defaults(): ConfigurationModel {
		return this._defaultConfiguration;
	}

	get user(): ConfigurationModel {
		return this._userConfiguration;
	}

	get workspace(): ConfigurationModel {
		return this._workspaceConfiguration;
	}

	protected get folders(): ResourceMap<ConfigurationModel> {
		return this._folderConfigurations;
	}

	private getConsolidateConfigurationModel(overrides: IConfigurationOverrides, workspace: Workspace): ConfigurationModel {
		let configurationModel = this.getConsolidatedConfigurationModelForResource(overrides, workspace);
		return overrides.overrideIdentifier ? configurationModel.override(overrides.overrideIdentifier) : configurationModel;
	}

	private getConsolidatedConfigurationModelForResource({ resource }: IConfigurationOverrides, workspace: Workspace): ConfigurationModel {
		let consolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();

		if (workspace && resource) {
			const root = workspace.getFolder(resource);
			if (root) {
				consolidateConfiguration = this.getFolderConsolidatedConfiguration(root.uri) || consolidateConfiguration;
			}
			const memoryConfigurationForResource = this._memoryConfigurationByResource.get(resource);
			if (memoryConfigurationForResource) {
				consolidateConfiguration = consolidateConfiguration.merge(memoryConfigurationForResource);
			}
		}

		return consolidateConfiguration;
	}

	private getWorkspaceConsolidatedConfiguration(): ConfigurationModel {
		if (!this._workspaceConsolidatedConfiguration) {
			this._workspaceConsolidatedConfiguration = this._defaultConfiguration.merge(this._userConfiguration, this._workspaceConfiguration, this._memoryConfiguration);
			if (this._freeze) {
				this._workspaceConfiguration = this._workspaceConfiguration.freeze();
			}
		}
		return this._workspaceConsolidatedConfiguration;
	}

	private getFolderConsolidatedConfiguration(folder: URI): ConfigurationModel {
		let folderConsolidatedConfiguration = this._foldersConsolidatedConfigurations.get(folder);
		if (!folderConsolidatedConfiguration) {
			const workspaceConsolidateConfiguration = this.getWorkspaceConsolidatedConfiguration();
			const folderConfiguration = this._folderConfigurations.get(folder);
			if (folderConfiguration) {
				folderConsolidatedConfiguration = workspaceConsolidateConfiguration.merge(folderConfiguration);
				if (this._freeze) {
					folderConsolidatedConfiguration = folderConsolidatedConfiguration.freeze();
				}
				this._foldersConsolidatedConfigurations.set(folder, folderConsolidatedConfiguration);
			} else {
				folderConsolidatedConfiguration = workspaceConsolidateConfiguration;
			}
		}
		return folderConsolidatedConfiguration;
	}

	private getFolderConfigurationModelForResource(resource: URI | undefined, workspace: Workspace): ConfigurationModel | null {
		if (workspace && resource) {
			const root = workspace.getFolder(resource);
			if (root) {
				return this._folderConfigurations.get(root.uri);
			}
		}
		return null;
	}

	toData(): IConfigurationData {
		return {
			defaults: {
				contents: this._defaultConfiguration.contents,
				overrides: this._defaultConfiguration.overrides,
				keys: this._defaultConfiguration.keys
			},
			user: {
				contents: this._userConfiguration.contents,
				overrides: this._userConfiguration.overrides,
				keys: this._userConfiguration.keys
			},
			workspace: {
				contents: this._workspaceConfiguration.contents,
				overrides: this._workspaceConfiguration.overrides,
				keys: this._workspaceConfiguration.keys
			},
			folders: this._folderConfigurations.keys().reduce((result, folder) => {
				const { contents, overrides, keys } = this._folderConfigurations.get(folder);
				result[folder.toString()] = { contents, overrides, keys };
				return result;
			}, Object.create({})),
			isComplete: true
		};
	}

	allKeys(workspace: Workspace): string[] {
		let keys = this.keys(workspace);
		let all = [...keys.default];
		const addKeys = (keys) => {
			for (const key of keys) {
				if (all.indexOf(key) === -1) {
					all.push(key);
				}
			}
		};
		addKeys(keys.user);
		addKeys(keys.workspace);
		for (const resource of this.folders.keys()) {
			addKeys(this.folders.get(resource).keys);
		}
		return all;
	}
}

export class AbstractConfigurationChangeEvent {

	protected doesConfigurationContains(configuration: ConfigurationModel, config: string): boolean {
		let changedKeysTree = configuration.contents;
		let requestedTree = toValuesTree({ [config]: true }, () => { });

		let key;
		while (typeof requestedTree === 'object' && (key = Object.keys(requestedTree)[0])) { // Only one key should present, since we added only one property
			changedKeysTree = changedKeysTree[key];
			if (!changedKeysTree) {
				return false; // Requested tree is not found
			}
			requestedTree = requestedTree[key];
		}
		return true;
	}

	protected updateKeys(configuration: ConfigurationModel, keys: string[], resource?: URI): void {
		for (const key of keys) {
			configuration.setValue(key, {});
		}
	}
}

export class ConfigurationChangeEvent extends AbstractConfigurationChangeEvent implements IConfigurationChangeEvent {

	private _source: ConfigurationTarget;
	private _sourceConfig: any;

	constructor(
		private _changedConfiguration: ConfigurationModel = new ConfigurationModel(),
		private _changedConfigurationByResource: ResourceMap<ConfigurationModel> = new ResourceMap<ConfigurationModel>()) {
		super();
	}

	get changedConfiguration(): IConfigurationModel {
		return this._changedConfiguration;
	}

	get changedConfigurationByResource(): ResourceMap<IConfigurationModel> {
		return this._changedConfigurationByResource;
	}

	change(event: ConfigurationChangeEvent): ConfigurationChangeEvent;
	change(keys: string[], resource?: URI): ConfigurationChangeEvent;
	change(arg1: any, arg2?: any): ConfigurationChangeEvent {
		if (arg1 instanceof ConfigurationChangeEvent) {
			this._changedConfiguration = this._changedConfiguration.merge(arg1._changedConfiguration);
			for (const resource of arg1._changedConfigurationByResource.keys()) {
				let changedConfigurationByResource = this.getOrSetChangedConfigurationForResource(resource);
				changedConfigurationByResource = changedConfigurationByResource.merge(arg1._changedConfigurationByResource.get(resource));
				this._changedConfigurationByResource.set(resource, changedConfigurationByResource);
			}
		} else {
			this.changeWithKeys(arg1, arg2);
		}
		return this;
	}

	telemetryData(source: ConfigurationTarget, sourceConfig: any): ConfigurationChangeEvent {
		this._source = source;
		this._sourceConfig = sourceConfig;
		return this;
	}

	get affectedKeys(): string[] {
		const keys = [...this._changedConfiguration.keys];
		this._changedConfigurationByResource.forEach(model => keys.push(...model.keys));
		return arrays.distinct(keys);
	}

	get source(): ConfigurationTarget {
		return this._source;
	}

	get sourceConfig(): any {
		return this._sourceConfig;
	}

	affectsConfiguration(config: string, resource?: URI): boolean {
		let configurationModelsToSearch: ConfigurationModel[] = [this._changedConfiguration];

		if (resource) {
			let model = this._changedConfigurationByResource.get(resource);
			if (model) {
				configurationModelsToSearch.push(model);
			}
		} else {
			configurationModelsToSearch.push(...this._changedConfigurationByResource.values());
		}

		for (const configuration of configurationModelsToSearch) {
			if (this.doesConfigurationContains(configuration, config)) {
				return true;
			}
		}

		return false;
	}

	private changeWithKeys(keys: string[], resource?: URI): void {
		let changedConfiguration = resource ? this.getOrSetChangedConfigurationForResource(resource) : this._changedConfiguration;
		this.updateKeys(changedConfiguration, keys);
	}

	private getOrSetChangedConfigurationForResource(resource: URI): ConfigurationModel {
		let changedConfigurationByResource = this._changedConfigurationByResource.get(resource);
		if (!changedConfigurationByResource) {
			changedConfigurationByResource = new ConfigurationModel();
			this._changedConfigurationByResource.set(resource, changedConfigurationByResource);
		}
		return changedConfigurationByResource;
	}
}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.8"/>
<title>LPM: Lagrangian Particle Methods: Data Fields</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

LPM: Lagrangian Particle Methods
    2.0

PDE solver

Main Page

Related Pages

Modules

Data Types List

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Data Types List

Data Types

Data Fields

All

Functions/Subroutines

Variables

a

b

c

d

e

f

g

h

i

k

l

m

n

o

p

q

r

s

t

u

v

w

x

y

z

 All Classes Files Functions Variables Modules Pages

Here is a list of all data types members with links to the data types they belong to:

- a -

absstream
: betaplanemeshmodule::betaplanemesh
, spherebvemodule::bvemesh

absvort
: betaplanemeshmodule::betaplanemesh
, spherebvemodule::bvemesh

absvortsource
: ssrfpackremeshmodule::bveremeshsource

addtracers()
: betaplanemeshmodule
, planarincompressiblemodule
, planarswemodule
, spherebvemodule
, sphereswemodule

advection_solver
: numberkindsmodule

amrlimit
: polymesh2dmodule::polymesh2d

area
: particlesmodule::particles
, planarincompressiblesolvermodule::planesolver
, spherebvesolvermodule::bvesolver

areafromleafedges()
: edgesmodule

areain
: sphereswesolvermodule::swesolver
, sweplanesolvermodule::swesolver

areastage1
: sphereswesolvermodule::swesolver
, sweplanesolvermodule::swesolver

areastage2
: sphereswesolvermodule::swesolver
, sweplanesolvermodule::swesolver

areastage3
: sphereswesolvermodule::swesolver
, sweplanesolvermodule::swesolver

areastage4
: sphereswesolvermodule::swesolver
, sweplanesolvermodule::swesolver

areastart
: sphereswesolvermodule::swesolver
, sweplanesolvermodule::swesolver

assignvectorfromcopy()
: stdintvectormodule

atan4()
: spheregeommodule

avgedgelength()
: edgesmodule

<address class="footer">
Generated on Tue Jan 12 2016 10:09:31 for LPM: Lagrangian Particle Methods by

 1.8.8
</address>


text:
/**
 * \file address.c
 * \brief Utility functions concernig addresses
 *
 * This file contains all the utility functions that can be used to
 * check, manipulate etc. addresses.
 */
#include "nsconfig.h"
#include "ns_types.h"
#include "ip6string.h"
#include "ns_trace.h"
#include "randLIB.h"
#include "string.h"
#include "nsdynmemLIB.h"
#include "ns_sha256.h"
#include "socket_api.h"
#include "Common_Protocols/ipv6_constants.h"
#include "Common_Protocols/icmpv6.h"
#include "Common_Protocols/mld.h"
#include "6LoWPAN/Thread/thread_common.h"
#include "common_functions.h"

#include "RPL/rpl_control.h"

#define TRACE_GROUP "addr"

typedef struct addr_notification {
    if_address_notification_fn *fn;
    ns_list_link_t link;
} addr_notification_t;

static NS_LIST_DEFINE(addr_notifications, addr_notification_t, link);

typedef struct addr_policy_table_entry_t {
    uint8_t prefix[16];
    uint8_t prefix_len;
    uint8_t precedence;
    uint8_t label;
    ns_list_link_t link;
} addr_policy_table_entry_t;

static NS_LIST_DEFINE(addr_policy_table, addr_policy_table_entry_t, link);

uint32_t addr_preferences_default = SOCKET_IPV6_PREFER_SRC_TMP | SOCKET_IPV6_PREFER_SRC_6LOWPAN_SHORT;

static void addr_policy_table_reset(void);
static void addr_max_entries_check(protocol_interface_info_entry_t *cur, if_address_source_t source);

const uint8_t ADDR_LINK_LOCAL_PREFIX[8]         = { 0xfe, 0x80 };
const uint8_t ADDR_SHORT_ADR_SUFFIC[6]          = { 0x00, 0x00, 0x00, 0xff, 0xfe, 0x00};

const uint8_t ADDR_MULTICAST_SOLICITED[13]      = { 0xff, 0x02, [11] = 0x01, 0xff};
const uint8_t ADDR_IF_LOCAL_ALL_NODES[16]       = { 0xff, 0x01, [15] = 0x01 };
const uint8_t ADDR_IF_LOCAL_ALL_ROUTERS[16]     = { 0xff, 0x01, [15] = 0x02 };
const uint8_t ADDR_LINK_LOCAL_ALL_NODES[16]     = { 0xff, 0x02, [15] = 0x01 };
const uint8_t ADDR_LINK_LOCAL_ALL_ROUTERS[16]   = { 0xff, 0x02, [15] = 0x02 };
const uint8_t ADDR_LINK_LOCAL_ALL_MLDV2_ROUTERS[16] = { 0xff, 0x02, [15] = 0x16 };
const uint8_t ADDR_LINK_LOCAL_MDNS[16]          = { 0xff, 0x02, [15] = 0xfb };
const uint8_t ADDR_REALM_LOCAL_ALL_NODES[16]    = { 0xff, 0x03, [15] = 0x01 };
const uint8_t ADDR_REALM_LOCAL_ALL_ROUTERS[16]  = { 0xff, 0x03, [15] = 0x02 };
const uint8_t ADDR_SITE_LOCAL_ALL_ROUTERS[16]   = { 0xff, 0x05, [15] = 0x02 };
const uint8_t ADDR_ALL_MPL_FORWARDERS[16]       = { 0xff, 0x03, [15] = 0xfc };
const uint8_t ADDR_ALL_DHCP_RELAY_AGENTS_AND_SERVERS[16] = { 0xff, 0x02, [13] = 0x01, 0x00, 0x02 };

const uint8_t ADDR_IPV4_MAPPED_PREFIX[12]       = { [10] = 0xff, 0xff };
const uint8_t ADDR_LOOPBACK[16]                 = { [15] = 1 };
const uint8_t ADDR_UNSPECIFIED[16]              = { 0 };        /* Note a few bits of code check for pointer equality with ADDR_UNSPECIFIED */
#define ADDR_IPV4_COMPATIBLE                    ADDR_LOOPBACK /* First 96 bits match...*/

#define ADDR_MULTICAST_LINK_PREFIX              ADDR_LINK_LOCAL_ALL_NODES /* ff02::xx */
#define ADDR_MULTICAST_REALM_PREFIX             ADDR_ALL_MPL_FORWARDERS /* ff03::xx */

static const uint8_t *addr_iid_secret_key;
static const uint8_t *addr_initial_iid;
static uint8_t addr_iid_secret_key_len;

static bool addr_am_implicit_group_member(const uint8_t group[static 16])
{
    static const uint8_t * const implicit_groups[] = {
        ADDR_LINK_LOCAL_ALL_NODES,
        ADDR_IF_LOCAL_ALL_NODES,
    };

    for (uint_fast8_t i = 0; i < sizeof implicit_groups / sizeof implicit_groups[0]; i++) {
        if (addr_ipv6_equal(implicit_groups[i], group)) {
            return true;
        }
    }
    return false;
}

uint8_t addr_len_from_type(addrtype_t addr_type)
{
    switch (addr_type) {
        case ADDR_NONE:
            return 0;
        case ADDR_802_15_4_SHORT:
            return 2 + 2; /* Some users don't have the PAN ID */
        case ADDR_802_15_4_LONG:
            return 2 + 8;
        case ADDR_EUI_48:
            return 6;
        case ADDR_IPV6:
            return 16;
        case ADDR_BROADCAST:
            return 0; /* Don't really handle this */
    }
    return 0;
}

/**
 * Check if an address is a broadcast address
 *
 * \param addr pointer to an address_t containing the address to be checked
 * \param addr_type the type of the address_t
 * \return 0 if the address is a broadcast address
 */
uint8_t addr_check_broadcast(const address_t addr, addrtype_t addr_type)
{
    switch (addr_type) {
        case ADDR_802_15_4_SHORT:
            break;
        case ADDR_BROADCAST:
            return 0;
        default:
            return 1;
    }

    uint8_t size = 2;
    uint8_t *ptr = (uint8_t *) addr;
    ptr += 2;

    while (size) {
        if ((*ptr++) != 0xFF) {
            break;
        } else {
            size--;
        }
    }
    return (size);

}

bool addr_is_ipv6_link_local(const uint8_t addr[static 16])
{
    return addr[0] == 0xfe && (addr[1] & 0xc0) == 0x80;
}

/* Site-local addresses deprecated, but still processed by RFC 6724 address selection */
static bool addr_is_ipv6_site_local(const uint8_t addr[static 16])
{
    return addr[0] == 0xfe && (addr[1] & 0xc0) == 0xc0;
}

static bool addr_is_ipv4_mapped(const uint8_t addr[static 16])
{
    return memcmp(addr, ADDR_IPV4_MAPPED_PREFIX, 12) == 0;
}

/* Scope(A), as defined in RFC 6724 plus RFC 4007 */
uint_fast8_t addr_ipv6_scope(const uint8_t addr[static 16], const protocol_interface_info_entry_t *interface)
{
    if (addr_is_ipv6_multicast(addr)) {
        return addr_ipv6_multicast_scope(addr);
    }
    if (addr_is_ipv6_link_local(addr) || addr_is_ipv6_loopback(addr)) {
        return IPV6_SCOPE_LINK_LOCAL;
    }
    if (addr_is_ipv6_site_local(addr)) {
        return IPV6_SCOPE_SITE_LOCAL;
    }
    /* Thread-specific hack - we want to treat one specific "mesh local" ULA as
     * "realm local" scope. (This is necessary, for example, to use a
     * mesh-local ULA address as source when sending realm-local multicast).
     */
    if (thread_addr_is_mesh_local(addr, interface)) {
        return IPV6_SCOPE_REALM_LOCAL;
    }
    if (addr_is_ipv4_mapped(addr)) {
        if ((addr[12] == 169 && addr[13] == 254) || addr[12] == 127) {
            return IPV6_SCOPE_LINK_LOCAL;
        }
        return IPV6_SCOPE_GLOBAL;
    }
    return IPV6_SCOPE_GLOBAL;
}

void address_module_init(void)
{
    addr_policy_table_reset();
    //mac_reset_short_address();
}

#ifdef MULTICAST_FORWARDING
static if_group_fwd_entry_t *addr_multicast_fwd_list_lookup(if_group_fwd_list_t *list, const uint8_t group[16])
{
    ns_list_foreach(if_group_fwd_entry_t, e, list) {
        if (addr_ipv6_equal(e->group, group)) {
            return e;
        }
    }
    return NULL;
}

bool addr_multicast_fwd_check(protocol_interface_info_entry_t *interface, const uint8_t group[16])
{
    return addr_multicast_fwd_list_lookup(&interface->ip_groups_fwd, group) != NULL;
}

static void addr_multicast_fwd_adjust_upstream(protocol_interface_info_entry_t *downstream, protocol_interface_info_entry_t *upstream, const uint8_t group[16], bool add)
{
    if (!upstream || downstream == upstream || !downstream->ip_multicast_forwarding) {
        return;
    }
    uint8_t group_scope = addr_ipv6_multicast_scope(group);
    if (downstream->zone_index[group_scope] == upstream->zone_index[group_scope]) {
        tr_debug("Multicast proxy %s %s", add ? "add" : "remove", trace_ipv6(group));
        if (add) {
            addr_add_group(upstream, group);
        } else {
            addr_remove_group(upstream, group);
        }
    }
}

void addr_multicast_fwd_adjust_upstream_full(protocol_interface_info_entry_t *upstream, bool add)
{
    ns_list_foreach(protocol_interface_info_entry_t, interface, &protocol_interface_info_list) {
        ns_list_foreach(if_group_fwd_entry_t, group, &interface->ip_groups_fwd) {
            addr_multicast_fwd_adjust_upstream(interface, upstream, group->group, add);
        }
    }
}

void addr_multicast_fwd_set_forwarding(struct protocol_interface_info_entry *interface, bool enable)
{
    /* Do nothing if enable state isn't changing */
    if (interface->ip_multicast_forwarding == enable) {
        return;
    }

    /* If we disable forwarding on upstream, clear it out to avoid maintenance confusion */
    if (!enable && interface == protocol_core_multicast_upstream) {
        multicast_fwd_set_proxy_upstream(-1);
    }

    /* Adjust routine checks that forwarding is on before doing any processing. So make sure it's on
     * now, then we'll set requested state afterwards. */
    interface->ip_multicast_forwarding = true;

    /* Add or remove all groups on changing downstream interface to upstream */
    if (protocol_core_multicast_upstream) {
        ns_list_foreach(if_group_fwd_entry_t, group, &interface->ip_groups_fwd) {
            addr_multicast_fwd_adjust_upstream(interface, protocol_core_multicast_upstream, group->group, enable);
        }
    }

    interface->ip_multicast_forwarding = enable;
}

bool addr_multicast_fwd_add(protocol_interface_info_entry_t *interface, const uint8_t group[16], uint32_t lifetime)
{
    if_group_fwd_entry_t *entry = addr_multicast_fwd_list_lookup(&interface->ip_groups_fwd, group);
    if (entry) {
        if (entry->lifetime < lifetime) {
            entry->lifetime = lifetime;
        }
        return true;
    }
    entry = ns_dyn_mem_alloc(sizeof *entry);
    if (!entry) {
        return false;
    }
    memcpy(entry->group, group, 16);
    ns_list_add_to_end(&interface->ip_groups_fwd, entry);
    addr_multicast_fwd_adjust_upstream(interface, protocol_core_multicast_upstream, group, true);
    entry->lifetime = lifetime;
    tr_debug("MC fwd added to IF %d: %s", interface->id, trace_ipv6(group));
    return true;
}

static void addr_multicast_fwd_delete_entry(protocol_interface_info_entry_t *interface, if_group_fwd_entry_t *entry)
{
    addr_multicast_fwd_adjust_upstream(interface, protocol_core_multicast_upstream, entry->group, false);
    ns_list_remove(&interface->ip_groups_fwd, entry);
    ns_dyn_mem_free(entry);
}

bool addr_multicast_fwd_remove(protocol_interface_info_entry_t *interface, const uint8_t group[16])
{
    if_group_fwd_entry_t *entry = addr_multicast_fwd_list_lookup(&interface->ip_groups_fwd, group);
    if (!entry) {
        return false;
    }

    tr_debug("MC fwd removed from IF %d: %s", interface->id, trace_ipv6(group));
    addr_multicast_fwd_delete_entry(interface, entry);

    return true;
}
#endif // MULTICAST_FORWARDING

int_fast8_t addr_policy_table_add_entry(const uint8_t *prefix, uint8_t len, uint8_t precedence, uint8_t label)
{
    addr_policy_table_entry_t *entry = ns_dyn_mem_alloc(sizeof(addr_policy_table_entry_t));
    if (!entry) {
        return -1;
    }
    bitcopy(entry->prefix, prefix, len);
    entry->prefix_len = len;
    entry->precedence = precedence;
    entry->label = label;

    /* Table is sorted longest-prefix-first, for longest-match searching */
    bool inserted = false;
    ns_list_foreach(addr_policy_table_entry_t, before, &addr_policy_table) {
        if (before->prefix_len > len) {
            continue;
        }
        if (before->prefix_len == len && bitsequal(before->prefix, prefix, len)) {
            ns_dyn_mem_free(entry);
            return -2;
        }
        ns_list_add_before(&addr_policy_table, before, entry);
        inserted = true;
        break;
    }

    if (!inserted) {
        ns_list_add_to_end(&addr_policy_table, entry);
    }

    return 0;
}

int_fast8_t addr_policy_table_delete_entry(const uint8_t *prefix, uint8_t len)
{
    ns_list_foreach(addr_policy_table_entry_t, entry, &addr_policy_table) {
        if (entry->prefix_len == len && bitsequal(entry->prefix, prefix, len)) {
            ns_list_remove(&addr_policy_table, entry);
            ns_dyn_mem_free(entry);
            return 0;
        }
    }

    return -1;
}
/// @TODO do we need this test print anymore ?
void addr_policy_table_print(void)
{
    ns_list_foreach(addr_policy_table_entry_t, entry, &addr_policy_table) {
        char addr[40];
        ip6tos(entry->prefix, addr);
        tr_debug("%3d %3d %s/%u\n", entry->precedence, entry->label, addr, entry->prefix_len);
    }
}

static void addr_policy_table_reset(void)
{
    ns_list_foreach_safe(addr_policy_table_entry_t, entry, &addr_policy_table) {
        ns_list_remove(&addr_policy_table, entry);
        ns_dyn_mem_free(entry);
    }

    /* Default policy table from RFC 6724 */
    addr_policy_table_add_entry(ADDR_LOOPBACK,                         128, 50 , 0);
    addr_policy_table_add_entry(NULL,                                    0, 40 , 1);
    addr_policy_table_add_entry(ADDR_IPV4_MAPPED_PREFIX,                96, 35,  4);
    addr_policy_table_add_entry((const uint8_t[]) { 0x20, 0x02 },       16, 30,  2);
    addr_policy_table_add_entry((const uint8_t[]) { 0x20, 0x01, 0, 0 }, 32,  5,  5);
    addr_policy_table_add_entry((const uint8_t[]) { 0xfc },              7,  3, 13);
    addr_policy_table_add_entry(ADDR_IPV4_COMPATIBLE,                   96,  1,  3);
    addr_policy_table_add_entry((const uint8_t[]) { 0xfe, 0xc0 },       10,  1, 11);
    addr_policy_table_add_entry((const uint8_t[]) { 0x3f, 0xfe },       16,  1, 12);
    //addr_policy_table_print();
}

static const addr_policy_table_entry_t *addr_get_policy(const uint8_t addr[static 16])
{
    ns_list_foreach(const addr_policy_table_entry_t, entry, &addr_policy_table) {
        if (bitsequal(entry->prefix, addr, entry->prefix_len)) {
            return entry;
        }
    }

    /* Shouldn't happen - should always have a default entry */
    return NULL;
}

/* RFC 6724 CommonPrefixLen(S, D) */
static uint_fast8_t addr_common_prefix_len(const uint8_t src[static 16], uint_fast8_t src_prefix_len, const uint8_t dst[static 16])
{
    uint_fast8_t common = 0;

    while (src_prefix_len >= 8 && *src == *dst) {
        common += 8;
        src_prefix_len -= 8;
        ++src;
        ++dst;
    }

    if (src_prefix_len) {
        uint8_t trail = common_count_leading_zeros_8(*src ^ *dst);
        if (trail > src_prefix_len) {
            trail = src_prefix_len;
        }
        common += trail;
    }

    return common;
}

if_address_entry_t *addr_get_entry(const protocol_interface_info_entry_t *interface, const uint8_t addr[static 16])
{
    ns_list_foreach(if_address_entry_t, entry, &interface->ip_addresses) {
        if (addr_ipv6_equal(entry->address, addr)) {
            return entry;
        }
    }

    return NULL;
}

bool addr_is_assigned_to_interface(const protocol_interface_info_entry_t *interface, const uint8_t addr[static 16])
{
    if_address_entry_t *entry = addr_get_entry(interface, addr);
    return entry && !entry->tentative;
}

bool addr_is_tentative_for_interface(const protocol_interface_info_entry_t *interface, const uint8_t addr[static 16])
{
    if_address_entry_t *entry = addr_get_entry(interface, addr);
    return entry && entry->tentative;
}

if_group_entry_t *addr_add_group(protocol_interface_info_entry_t *interface, const uint8_t group[static 16])
{
    if_group_entry_t *entry = addr_get_group_entry(interface, group);
    if (entry) {
        if (entry->ref_count != 0xFFFF) {
            entry->ref_count++;
        }
        return entry;
    }

    if (!addr_is_ipv6_multicast(group)) {
        return NULL;
    }

    if (addr_am_implicit_group_member(group)) {
        return NULL;
    }

    entry = ns_dyn_mem_alloc(sizeof(if_group_entry_t));
    if (!entry) {
        return NULL;
    }
    memcpy(entry->group, group, 16);
    entry->ref_count = 1;
    ns_list_add_to_end(&interface->ip_groups, entry);

    mld_start_listening(interface, entry);

    return entry;
}

/* This does reference count */
void addr_remove_group(protocol_interface_info_entry_t *interface, const uint8_t group[static 16])
{
    if_group_entry_t *entry = addr_get_group_entry(interface, group);
    if (entry) {
        if (entry->ref_count != 0xFFFF) {
            if (--entry->ref_count == 0) {
                addr_delete_group_entry(interface, entry);
            }
        }
    }
}

/* This does NOT reference count - it actually deletes the entry */
void addr_delete_group_entry(protocol_interface_info_entry_t *interface, if_group_entry_t *entry)
{
    mld_stop_listening(interface, entry);
    ns_list_remove(&interface->ip_groups, entry);
    ns_dyn_mem_free(entry);
}

void addr_delete_group(protocol_interface_info_entry_t *interface, const uint8_t group[static 16])
{
    if_group_entry_t *entry = addr_get_group_entry(interface, group);
    if (entry) {
        addr_delete_group_entry(interface, entry);
    }
}

if_group_entry_t *addr_get_group_entry(const protocol_interface_info_entry_t *interface, const uint8_t group[static 16])
{
    ns_list_foreach(if_group_entry_t, entry, &interface->ip_groups) {
        if (addr_ipv6_equal(entry->group, group)) {
            return entry;
        }
    }

    return NULL;
}

static void addr_generate_solicited_node_group(uint8_t group[static 16], const uint8_t addr[static 16])
{
    memcpy(group, ADDR_MULTICAST_SOLICITED, 13);
    memcpy(group + 13, addr + 13, 3);
}

static if_group_entry_t *addr_add_solicited_node_group(protocol_interface_info_entry_t *interface, const uint8_t address[static 16])
{
    uint8_t group[16];
    addr_generate_solicited_node_group(group, address);
    return addr_add_group(interface, group);
}

static void addr_remove_solicited_node_group(protocol_interface_info_entry_t *interface, const uint8_t address[static 16])
{
    uint8_t group[16];
    addr_generate_solicited_node_group(group, address);
    addr_remove_group(interface, group);
}

void addr_add_router_groups(protocol_interface_info_entry_t *interface)
{
    /* The standard IPv6 ones, but not "Realm-Local-All-Routers"
     * which is ZigBee IP / Thread-specific (and not IANA registered)
     */
    addr_add_group(interface, ADDR_IF_LOCAL_ALL_ROUTERS);
    addr_add_group(interface, ADDR_LINK_LOCAL_ALL_ROUTERS);

    /* We only want to join the site address on one interface per site zone,
     * or we'd get multiple copies of packets. Exit if we're already a member.
     */
    ns_list_foreach(protocol_interface_info_entry_t, i, &protocol_interface_info_list) {
        if (i->zone_index[IPV6_SCOPE_SITE_LOCAL] == interface->zone_index[IPV6_SCOPE_SITE_LOCAL] &&
                addr_get_group_entry(i, ADDR_SITE_LOCAL_ALL_ROUTERS)) {
            return;
        }
    }
    addr_add_group(interface, ADDR_SITE_LOCAL_ALL_ROUTERS);
}

bool addr_am_group_member_on_interface(const protocol_interface_info_entry_t *interface, const uint8_t group[static 16])
{
    return addr_am_implicit_group_member(group) || addr_get_group_entry(interface, group);
}

/* RFC 6724 Default source address selection */
const uint8_t *addr_select_source(protocol_interface_info_entry_t *interface, const uint8_t dest[static 16], uint32_t addr_preferences)
{
    /* Let's call existing preferred address "SA" and new candidate "SB", to
     * make it look like a bit like RFC 6724
     */
    if_address_entry_t *SA = NULL;
    uint_fast8_t scope_D = addr_ipv6_scope(dest, interface);
    const addr_policy_table_entry_t *policy_D = addr_get_policy(dest);

    if (addr_preferences == 0) {
        addr_preferences = addr_preferences_default;
    }

    /*
     * As we go around the loop, if we prefer the new "SB", we set SA to SB
     * and continue. If we decide we prefer the existing SA, we just continue.
     *
     * Careful with these macros - they must only be used with if/else, and
     * inside { }, as per the coding style rules.
     */
#define PREFER_SA continue
#define PREFER_SB SA = SB; continue

    ns_list_foreach(if_address_entry_t, SB, &interface->ip_addresses) {
        /* Ignore tentative addresses */
        if (SB->tentative) {
            continue;
        }

        /* First (non-tentative) address seen becomes SA */
        if (!SA) {
            PREFER_SB;
        }

        /* Rule 1: Prefer same address */
        if (memcmp(SB->address, dest, 16) == 0) {
            SA = SB;
            /* It's an exact match, no point checking any other addresses */
            break;
        }

        /* Rule 2: Prefer appropriate scope */
        uint_fast8_t scope_SA = addr_ipv6_scope(SA->address, interface);
        uint_fast8_t scope_SB = addr_ipv6_scope(SB->address, interface);
        if (scope_SA < scope_SB) {
            if (scope_SA < scope_D) {
                PREFER_SB;
            } else {
                PREFER_SA;
            }
        } else if (scope_SB < scope_SA) {
            if (scope_SB < scope_D) {
                PREFER_SA;
            } else {
                PREFER_SB;
            }
        }

        /* Rule 3: Avoid deprecated addresses */
        if (SA->preferred_lifetime != 0 && SB->preferred_lifetime == 0) {
            PREFER_SA;
        } else if (SB->preferred_lifetime != 0 && SA->preferred_lifetime == 0) {
            PREFER_SB;
        }

        /* (Rule 4: Prefer home addresses - Mobile IPv6 not implemented) */
        /* (Rule 5: Prefer outgoing interface - candidate set already limited) */
        /* (Rule 5.5: Prefer addresses in a prefix advertised by the next-hop - we don't track this information) */

        /* Rule 6: Prefer matching label */
        const addr_policy_table_entry_t *policy_SA = addr_get_policy(SA->address);
        const addr_policy_table_entry_t *policy_SB = addr_get_policy(SB->address);
        if (policy_SA->label == policy_D->label && policy_SB->label != policy_D->label) {
            PREFER_SA;
        } else if (policy_SB->label == policy_D->label && policy_SA->label != policy_D->label) {
            PREFER_SB;
        }

        /* Rule 7: Prefer temporary addresses (or the opposite) */
        if (SA->temporary != SB->temporary) {
            bool prefer_public = (addr_preferences & SOCKET_IPV6_PREFER_SRC_PUBLIC);

            if (SA->temporary != prefer_public) {
                PREFER_SA;
            } else {
                PREFER_SB;
            }
        }

        /* Rule 8: Use longest matching prefix */
        uint_fast8_t common_SA = addr_common_prefix_len(SA->address, SA->prefix_len, dest);
        uint_fast8_t common_SB = addr_common_prefix_len(SB->address, SB->prefix_len, dest);
        if (common_SA > common_SB) {
            PREFER_SA;
        } else if (common_SB > common_SA) {
            PREFER_SB;
        }

        /* A tie-breaker: Prefer 6LoWPAN short address (or the opposite) */
        bool short_SA = SA->prefix_len == 64 && memcmp(SA->address + 8, ADDR_SHORT_ADR_SUFFIC, 6) == 0;
        bool short_SB = SB->prefix_len == 64 && memcmp(SB->address + 8, ADDR_SHORT_ADR_SUFFIC, 6) == 0;
        if (short_SA != short_SB) {
            bool prefer_short = (addr_preferences & SOCKET_IPV6_PREFER_SRC_6LOWPAN_SHORT);

            if (short_SA == prefer_short) {
                PREFER_SA;
            } else {
                PREFER_SB;
            }
        }

        /* Tie */
        PREFER_SA;
    }

    return SA ? SA->address : NULL;
}

/* A variant of RFC 6724 Default source address selection, to select an address
 * on an interface with a specific prefix. The prefix must match, and some
 * source address rules don't apply, but some are handled similarly. See
 * comments in addr_select_source.
 */
const uint8_t *addr_select_with_prefix(protocol_interface_info_entry_t *cur, const uint8_t *prefix, uint8_t prefix_len, uint32_t addr_preferences)
{
    if_address_entry_t *SA = NULL;

    if (addr_preferences == 0) {
        addr_preferences = addr_preferences_default;
    }

    ns_list_foreach(if_address_entry_t, SB, &cur->ip_addresses) {
        /* Ignore tentative addresses */
        if (SB->tentative) {
            continue;
        }

        /* Prefix must match */
        if (!bitsequal(SB->address, prefix, prefix_len)) {
            continue;
        }

        /* First (non-tentative, matching prefix) address seen becomes SA */
        if (!SA) {
            PREFER_SB;
        }

        /* (Rule 1: Prefer same address - doesn't apply here) */
        /* Rule 2: Was prefer appropriate scope - for this purpose we instead prefer wider scope */
        uint_fast8_t scope_SA = addr_ipv6_scope(SA->address, cur);
        uint_fast8_t scope_SB = addr_ipv6_scope(SB->address, cur);
        if (scope_SA < scope_SB) {
            PREFER_SB;
        } else if (scope_SB < scope_SA) {
            PREFER_SA;
        }

        /* Rule 3: Avoid deprecated addresses */
        if (SA->preferred_lifetime != 0 && SB->preferred_lifetime == 0) {
            PREFER_SA;
        }
        else if (SB->preferred_lifetime != 0 && SA->preferred_lifetime == 0) {
            PREFER_SB;
        }

        /* (Rule 4: Prefer home addresses - Mobile IPv6 not implemented) */
        /* (Rule 5: Prefer outgoing interface - candidate set already limited) */
        /* (Rule 5.5: Prefer addresses in a prefix advertised by the next-hop - we don't track this information) */

        /* Rule 6: Prefer matching label - doesn't apply here. But instead,
         * let's use precedence, like rule 6 of destination selection.
         */
        const addr_policy_table_entry_t *policy_SA = addr_get_policy(SA->address);
        const addr_policy_table_entry_t *policy_SB = addr_get_policy(SB->address);
        if (policy_SA->precedence > policy_SB->precedence) {
            PREFER_SA;
        } else if (policy_SB->precedence > policy_SA->precedence) {
            PREFER_SB;
        }

        /* Rule 7: Prefer temporary addresses (or the opposite) */
        if (SA->temporary != SB->temporary) {
            bool prefer_public = (addr_preferences & SOCKET_IPV6_PREFER_SRC_PUBLIC);

            if (SA->temporary != prefer_public) {
                PREFER_SA;
            } else {
                PREFER_SB;
            }
        }

        /* (Rule 8: Use longest matching prefix - doesn't apply) */

        /* A tie-breaker: Prefer 6LoWPAN short address (or the opposite) */
        bool short_SA = SA->prefix_len == 64 && memcmp(SA->address + 8, ADDR_SHORT_ADR_SUFFIC, 6) == 0;
        bool short_SB = SB->prefix_len == 64 && memcmp(SB->address + 8, ADDR_SHORT_ADR_SUFFIC, 6) == 0;
        if (short_SA != short_SB) {
            bool prefer_short = (addr_preferences & SOCKET_IPV6_PREFER_SRC_6LOWPAN_SHORT);

            if (short_SA == prefer_short) {
                PREFER_SA;
            } else {
                PREFER_SB;
            }
        }

        /* Tie */
        PREFER_SA;
    }

    return SA ? SA->address : NULL;
}

#undef PREFER_SA
#undef PREFER_SB

void addr_delete_entry(protocol_interface_info_entry_t *cur, if_address_entry_t *addr)
{
    if (addr->group_added) {
        addr_remove_solicited_node_group(cur, addr->address);
    }
    ns_list_remove(&cur->ip_addresses, addr);
    addr_cb(cur, addr, ADDR_CALLBACK_DELETED);
    ns_dyn_mem_free(addr);
}

/* ticks is in 1/10s */
void addr_fast_timer(protocol_interface_info_entry_t *cur, uint_fast16_t ticks)
{
    /* Fast timers only run while the interface is active. */
    if (!(cur->lowpan_info & INTERFACE_NWK_ACTIVE)) {
        return;
    }

    ns_list_foreach_safe(if_address_entry_t, addr, &cur->ip_addresses) {
        if (addr->state_timer == 0) {
            continue;
        }

        if (addr->state_timer > ticks) {
            addr->state_timer -= ticks;
            continue;
        }

        addr->state_timer = 0;
        /* Advance DAD state machine if tentative, else give it to the protocol state machine */
        if (addr->tentative) {
            if (addr->count == 0) {
#if 0
                // Initial join delay finished
                // We don't have full MLD support - send 1 report for now
                // This will become a real "join" later
                buffer_t *mld_buf;
                uint8_t sol_addr[16];
                memcpy(sol_addr, ADDR_MULTICAST_SOLICITED, 13);
                memcpy(sol_addr + 13, addr->address + 13, 3);
                mld_buf = mld_build(cur, NULL, ICMPV6_TYPE_INFO_MCAST_LIST_REPORT, 0, sol_addr);
                protocol_push(mld_buf);
#endif
                if (addr_add_solicited_node_group(cur, addr->address)) {
                    addr->group_added = true;
                }
            }
#ifdef HAVE_IPV6_ND
            if (addr->count >= cur->dup_addr_detect_transmits) {
                /* Finished - if we've not been nerfed already, we can transition
                 * to non-tentative.
                 */
                addr->tentative = false;
                addr->count = 0;
                tr_info("DAD passed on IF %d: %s", cur->id, trace_ipv6(addr->address));
                addr_cb(cur, addr, ADDR_CALLBACK_DAD_COMPLETE);
            } else {
                buffer_t *ns_buf = icmpv6_build_ns(cur, addr->address, NULL, false, true, NULL);
                protocol_push(ns_buf);
                addr->state_timer = (cur->ipv6_neighbour_cache.retrans_timer + 50) / 100; // ms -> ticks
                addr->count++;
            }
#endif
        } else {
            addr_cb(cur, addr, ADDR_CALLBACK_TIMER);
        }

        /* If a callback has shut down the interface, break now - this isn't
         * just a nicety; it avoids an iteration failure if shutdown disrupted
         * the address list (as is likely).
         */
        if (!(cur->lowpan_info & INTERFACE_NWK_ACTIVE)) {
            break;
        }
    }
}

void addr_slow_timer(protocol_interface_info_entry_t *cur, uint_fast16_t seconds)
{
    /* Slow (lifetime) timers run whether the interface is active or not */
    ns_list_foreach_safe(if_address_entry_t, addr, &cur->ip_addresses) {
        if (addr->preferred_lifetime != 0xffffffff && addr->preferred_lifetime != 0) {
            if (addr->preferred_lifetime > seconds) {
                addr->preferred_lifetime -= seconds;
            } else {
                tr_info("Address deprecated: %s", trace_ipv6(addr->address));
                addr->preferred_lifetime = 0;
                addr_cb(cur, addr, ADDR_CALLBACK_DEPRECATED);
            }
        }

        if (addr->valid_lifetime != 0xffffffff) {
            if (addr->valid_lifetime > seconds) {
                addr->valid_lifetime -= seconds;
            } else {
                tr_info("Address invalidated: %s", trace_ipv6(addr->address));
                addr->valid_lifetime = 0;
                addr_cb(cur, addr, ADDR_CALLBACK_INVALIDATED);
                /* Give them the chance to revalidate */
                if (addr->valid_lifetime == 0) {
                    addr_delete_entry(cur, addr);
                }
            }
        }
    }

#ifdef MULTICAST_FORWARDING
    ns_list_foreach_safe(if_group_fwd_entry_t, group, &cur->ip_groups_fwd) {
        if (group->lifetime != 0xffffffff) {
            if (group->lifetime > seconds) {
                group->lifetime -= seconds;
            } else {
                tr_debug("MC fwd expired: %s", trace_ipv6(group->group));
                addr_multicast_fwd_delete_entry(cur, group);
            }
        }
    }
#endif
}

static void addr_max_entries_check(protocol_interface_info_entry_t *cur, if_address_source_t source)
{
    // Limit only auto configuration addresses
    if (source != ADDR_SOURCE_SLAAC || cur->ip_addresses_max_slaac_entries == 0) {
        return;
    }

    uint8_t count = 0;
    if_address_entry_t *first_slaac_entry = NULL;
    ns_list_foreach(if_address_entry_t, e, &cur->ip_addresses) {
        if (e->source == ADDR_SOURCE_SLAAC) {
            if (!first_slaac_entry) {
                first_slaac_entry = e;
            }
            if (++count == 0xff) {
                break;
            }
        }
    }

    if (count > cur->ip_addresses_max_slaac_entries) {
        addr_delete_entry(cur, first_slaac_entry);
    }
}

void addr_max_slaac_entries_set(protocol_interface_info_entry_t *cur, uint8_t max_slaac_entries)
{
    cur->ip_addresses_max_slaac_entries = max_slaac_entries;
}

if_address_entry_t *addr_add(protocol_interface_info_entry_t *cur, const uint8_t address[static 16], uint_fast8_t prefix_len, if_address_source_t source, uint32_t valid_lifetime, uint32_t preferred_lifetime, bool skip_dad)
{
    if (addr_get_entry(cur, address)) {
        return NULL;
    }

    addr_max_entries_check(cur, source);

    if_address_entry_t *entry = ns_dyn_mem_alloc(sizeof(if_address_entry_t));
    if (!entry) {
        return NULL;
    }

    memset(entry, 0, sizeof *entry);
    entry->cb = NULL;
    memcpy(entry->address, address, 16);
    entry->prefix_len = prefix_len;
    entry->source = source;
    entry->valid_lifetime = valid_lifetime;
    entry->preferred_lifetime = preferred_lifetime;
    entry->group_added = false;
#ifndef HAVE_IPV6_ND
    skip_dad = true;
#endif
    if (skip_dad || cur->dup_addr_detect_transmits == 0) {
        entry->tentative = false;
        if (addr_add_solicited_node_group(cur, entry->address)) {
            entry->group_added = true;
        }
        // XXX not right? Want to do delay + MLD join, so don't special-case?
        /* entry->cb isn't set yet, but global notifiers will want call */
        addr_cb(cur, entry, ADDR_CALLBACK_DAD_COMPLETE);
    } else {
        entry->tentative = true;
        // Initial timer is for the multicast join delay
        entry->count = 0;
        entry->state_timer = randLIB_get_random_in_range(1, 10); // MAX_RTR_SOLICITATION_DELAY (1s) in ticks
    }

    tr_info("%sAddress added to IF %d: %s", (entry->tentative ? "Tentative " : ""), cur->id, trace_ipv6(address));

    ns_list_add_to_end(&cur->ip_addresses, entry);

    return entry;
}

int_fast8_t addr_delete(protocol_interface_info_entry_t *cur, const uint8_t address[static 16])
{
    ns_list_foreach(if_address_entry_t, e, &cur->ip_addresses) {
        if (memcmp(e->address, address, 16) == 0) {
            addr_delete_entry(cur, e);
            return 0;
        }
    }

    return -1;
}

void addr_delete_matching(protocol_interface_info_entry_t *cur, const uint8_t *prefix, uint8_t prefix_len, if_address_source_t source)
{
    ns_list_foreach_safe(if_address_entry_t, e, &cur->ip_addresses) {
        if ((source == ADDR_SOURCE_UNKNOWN || e->source == source) &&
                bitsequal(e->address, prefix, prefix_len)) {
            addr_delete_entry(cur, e);
        }
    }

}

void addr_set_non_preferred(protocol_interface_info_entry_t *cur, if_address_source_t source)
{
    ns_list_foreach_safe(if_address_entry_t, e, &cur->ip_addresses) {
        if (e->source == source) {
            // Sets preferred lifetime to zero or deletes tentative addresses
            addr_set_preferred_lifetime(cur, e, 0);
        }
    }
}

void addr_duplicate_detected(struct protocol_interface_info_entry *interface, const uint8_t addr[static 16])
{
    if_address_entry_t *entry = addr_get_entry(interface, addr);
    if (!entry) {
        return;
    }

    tr_warn("DAD failed: %s", trace_ipv6(addr));

    interface->dad_failures++;
    addr_cb(interface, entry, ADDR_CALLBACK_DAD_FAILED);

    /* Callback may have done something drastic like shut down the interface.
     * Don't assume entry is still valid - remove it by IP address.
     */
    addr_delete(interface, addr);
}

void addr_notification_register(if_address_notification_fn *fn)
{
    ns_list_foreach(addr_notification_t, n, &addr_notifications) {
        if (n->fn == fn) {
            return;
        }
    }

    addr_notification_t *n = ns_dyn_mem_alloc(sizeof(addr_notification_t));
    if (!n) {
        tr_error("addr_notification_register mem");
        return;
    }
    n->fn = fn;
    ns_list_add_to_end(&addr_notifications, n);
}

void addr_cb(protocol_interface_info_entry_t *interface, if_address_entry_t *addr, if_address_callback_t reason)
{
    ns_list_foreach(addr_notification_t, n, &addr_notifications) {
        n->fn(interface, addr, reason);
    }
    if (addr->cb) {
        addr->cb(interface, addr, reason);
    }
}

void addr_set_valid_lifetime(protocol_interface_info_entry_t *interface, if_address_entry_t *addr, uint32_t valid_lifetime)
{
    if (valid_lifetime != addr->valid_lifetime) {
        addr->valid_lifetime = valid_lifetime;
        addr_cb(interface, addr, ADDR_CALLBACK_REFRESHED);
    }
}

void addr_set_preferred_lifetime(protocol_interface_info_entry_t *interface, if_address_entry_t *addr, uint32_t preferred_lifetime)
{
    if (preferred_lifetime != addr->preferred_lifetime) {
        addr->preferred_lifetime = preferred_lifetime;
        if (preferred_lifetime == 0) {
            // Entry is deleted if it is tentative
            if (addr->tentative) {
                addr_delete_entry(interface, addr);
            } else {
                addr_cb(interface, addr, ADDR_CALLBACK_DEPRECATED);
            }
        }
    }
}

void memswap(uint8_t *restrict a, uint8_t *restrict b, uint_fast8_t len)
{
    while (len--) {
        uint8_t t = *a;
        *a++ = *b;
        *b++ = t;
    }
}

/* Optimised for quick discard of mismatching addresses (eg in a cache lookup):
 * searches BACKWARDS, as last bytes are most likely to differ.
 */
bool addr_ipv6_equal(const uint8_t a[static 16], const uint8_t b[static 16])
{
    for (int_fast8_t n = 15; n >= 0; n--) {
        if (a[n] != b[n]) {
            return false;
        }
    }
    return true;
}

bool addr_iid_matches_eui64(const uint8_t iid[static 8], const uint8_t eui64[static 8])
{
    for (int_fast8_t n = 7; n >= 1; n--) {
        if (iid[n] != eui64[n]) {
            return false;
        }
    }
    return iid[0] == (eui64[0] ^ 2);
}

bool addr_iid_matches_lowpan_short(const uint8_t iid[static 8], uint16_t short_addr)
{
    if (iid[7] != (short_addr & 0xFF) ||
            iid[6] != (short_addr >> 8)) {
        return false;
    }

    for (int_fast8_t n = 5; n >= 0; n--) {
        if (iid[n] != ADDR_SHORT_ADR_SUFFIC[n]) {
            return false;
        }
    }
    return true;
}

bool addr_iid_reserved(const uint8_t iid[static 8])
{
    static const uint8_t reserved_iana[5] = { 0x02, 0x00, 0x5e, 0xff, 0xfe };
    static const uint8_t reserved_subnet_anycast[7] = { 0xfd, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

    if (memcmp(iid, ADDR_UNSPECIFIED + 8, 8) == 0) {
        return true; // subnet-router anycast
    }

    if (memcmp(iid, reserved_iana, 5) == 0) {
        return true;
    }

    if (memcmp(iid, reserved_subnet_anycast, 7) == 0 && iid[7] >= 0x80) {
        return true;
    }

    return false;
}

int_fast8_t addr_opaque_iid_key_set(const void *secret_key, uint8_t key_len)
{
    /* Delete existing info */
    if (addr_iid_secret_key) {
        ns_dyn_mem_free((void *) addr_iid_secret_key);
        addr_iid_secret_key = NULL;
        addr_iid_secret_key_len = 0;
    }

    /* If disabling, that's it */
    if (secret_key == NULL) {
        return 0;
    }
    /* Attempt to copy new info */
    uint8_t *copy = ns_dyn_mem_alloc(key_len);
    if (!copy) {
        return -1;
    }
    addr_iid_secret_key = memcpy(copy, secret_key, key_len);
    addr_iid_secret_key_len = key_len;
    return 0;
}

int_fast8_t addr_opaque_initial_iid_set(const void *iid)
{
    /* Delete existing info */
    if (addr_initial_iid) {
        ns_dyn_mem_free((void *) addr_initial_iid);
        addr_initial_iid = NULL;
    }
    if (!iid) {
        return 0;
    }
    /* Attempt to copy new info */
    uint8_t *copy = ns_dyn_mem_alloc(8);
    if (!copy) {
        return -1;
    }
    addr_initial_iid = memcpy(copy, iid, 8);
    return 0;
}

bool addr_opaque_iid_key_is_set(void)
{
    return addr_iid_secret_key != NULL;
}

/* RFC 7217 generation: addr must be prepopulated with 8-byte prefix, and secret key must be set */
void addr_generate_opaque_iid(protocol_interface_info_entry_t *cur, uint8_t addr[static 16])
{
opaque_retry:

    if (addr_initial_iid && !cur->dad_failures) {
        // This is test implementations use only normally should not need this.
        memcpy(addr + 8,addr_initial_iid,8);
        return;
    }
    {
        // Limit scope to try to minimise stack, given the goto
        ns_sha256_context ctx;
        ns_sha256_init(&ctx);
        ns_sha256_starts(&ctx);
        ns_sha256_update(&ctx, addr, 8);
        if (cur->interface_name) {
            /* This isn't ideal - there's no guarantee each instance of a driver has a distinct name */
            ns_sha256_update(&ctx, cur->interface_name, strlen(cur->interface_name));
        } else {
            ns_sha256_update(&ctx, &cur->id, sizeof cur->id);
        }
        ns_sha256_update(&ctx, &cur->dad_failures, sizeof cur->dad_failures);
        ns_sha256_update(&ctx, addr_iid_secret_key, addr_iid_secret_key_len);
        ns_sha256_finish_nbits(&ctx, addr + 8, 64);
        ns_sha256_free(&ctx);
    }
    /* Note that we only check for reserved IIDs - as per RFC 7217,
     * there's no restriction on U/G bits.
     */
    if (addr_iid_reserved(addr + 8)) {
        cur->dad_failures++;
        goto opaque_retry;
    }
}

/* Write a LoWPAN IPv6 address, based on a prefix and short address */
uint8_t *addr_ipv6_write_from_lowpan_short(uint8_t dst[static 16], const uint8_t prefix[static 8], uint16_t short_addr)
{
    common_write_16_bit(short_addr, dst + 14);
    memcpy(dst + 8, ADDR_SHORT_ADR_SUFFIC, 6);
    return memcpy(dst, prefix, 8);
}

/* Turn an address (either MAC or IP) into a base IP address for context compression */
bool addr_iid_from_outer(uint8_t iid_out[static 8], const sockaddr_t *addr_in)
{
    switch (addr_in->addr_type) {
        case ADDR_802_15_4_LONG:
            memcpy(iid_out, addr_in->address + 2, 8);
            iid_out[0] ^= 2;
            break;
        case ADDR_BROADCAST:
        case ADDR_802_15_4_SHORT:
            memcpy(iid_out, ADDR_SHORT_ADR_SUFFIC, 6);
            iid_out[6] = addr_in->address[2];
            iid_out[7] = addr_in->address[3];
            break;
        case ADDR_IPV6:
            memcpy(iid_out, addr_in->address + 8, 8);
            break;
        default:
            return false;
    }

    return true;
}

int addr_interface_set_ll64(protocol_interface_info_entry_t *cur, if_address_callback_fn *cb)
{
    int ret_val = -1;
    if_address_entry_t *address_entry = NULL;
    uint8_t temp_ll64[16];
    memcpy(temp_ll64, ADDR_LINK_LOCAL_PREFIX, 8);
    memcpy(temp_ll64 + 8, cur->iid_eui64, 8);

    address_entry = addr_add(cur, temp_ll64, 64, ADDR_SOURCE_UNKNOWN, 0xffffffff, 0xffffffff, false);
    if (address_entry) {
        tr_debug("LL64 Register OK!");
        ret_val = 0;
        address_entry->cb = cb;
        if (!address_entry->tentative) {
            addr_cb(cur, address_entry, ADDR_CALLBACK_DAD_COMPLETE);
        }
    }
    return ret_val;
}

/* address_type 0 means "any" address - we return short by preference */
/* address_type 1 means long address - we ignore short addresses */
int8_t addr_interface_get_ll_address(protocol_interface_info_entry_t *cur, uint8_t *address_ptr, uint8_t address_type)
{
    const uint8_t *short_addr = NULL;
    const uint8_t *long_addr = NULL;

    if (!cur) {
        return -1;
    }

    ns_list_foreach(if_address_entry_t, e, &cur->ip_addresses) {
        if (!e->tentative && addr_is_ipv6_link_local(e->address)) {
            if (cur->nwk_id == IF_6LoWPAN && memcmp(e->address + 8, ADDR_SHORT_ADR_SUFFIC, 6) == 0) {
                short_addr = e->address;
            } else {
                long_addr = e->address;
            }

            if (long_addr && short_addr) {
                break;
            }
        }
    }

    if (short_addr && address_type != 1) {
        if (address_ptr) {
            memcpy(address_ptr, short_addr, 16);
        }
        return 0;
    } else if (long_addr) {
        if (address_ptr) {
            memcpy(address_ptr, long_addr, 16);
        }
        return 0;
    } else {
        return -1;
    }
}

bool addr_interface_all_address_ready(protocol_interface_info_entry_t *cur)
{
    if (!cur) {
        return false;
    }

    ns_list_foreach(if_address_entry_t, e, &cur->ip_addresses) {
        if (e->tentative) {
            return false;
        }
    }
    return true;
}

int8_t addr_interface_gp_prefix_compare(protocol_interface_info_entry_t *cur, const uint8_t *prefix)
{
    if (cur->global_address_available) {
        ns_list_foreach(if_address_entry_t, e, &cur->ip_addresses) {
            if (memcmp(e->address, prefix, 8) == 0) {
                return 0;
            }
        }
    }
    return -1;
}

int8_t addr_interface_address_compare(protocol_interface_info_entry_t *cur, const uint8_t *addr)
{
    /* First check the specified interface */
    if (addr_is_assigned_to_interface(cur, addr)) {
        return 0;
    }

    /* If link-local, that's it */
    if (addr_is_ipv6_link_local(addr)) {
        return -1;
    }

    /* Now check other interfaces */
    /* TODO: should only do this if both current and other interface have forwarding enabled */
    return protcol_interface_address_compare(cur, addr);
}

int8_t addr_interface_select_source(protocol_interface_info_entry_t *cur, uint8_t *src_ptr, const uint8_t *dest, uint32_t addr_preferences)
{
    int8_t ret_val = -1;
    if (cur) {
        const uint8_t *src = addr_select_source(cur, dest, addr_preferences);
        if (src) {
            memcpy(src_ptr, src, 16);
            ret_val = 0;
        }
    }
    return ret_val;
}

// This last function must always be compiled with tracing enabled
#ifndef FEA_TRACE_SUPPORT
#define FEA_TRACE_SUPPORT 1
#include "mbed-trace/mbed_trace.h"
#endif
char* trace_sockaddr(const sockaddr_t* addr, bool panid_prefix)
{
    uint8_t length = addr_len_from_type(addr->addr_type);

    if (length == 0) {
        return "<n/a>";
    }

    /* Awkward hack for 802.15.4 address types */
    if (addr->addr_type == ADDR_802_15_4_SHORT ||
        addr->addr_type == ADDR_802_15_4_LONG) {
        length -= (panid_prefix) ? 0 : 2;
    }

    /* Start from index 0 (prints PAN ID if exists) */
    return trace_array(&addr->address[0], length);
}


text:
- Currently supports cloning all user repos

## Setup

    cd && git clone https://github.com/manojpandey/ghterm.git
    virtualenv venv
    source venv/bin/activate
    python clone.py <username of your github account>

## Contribution

- Open any issue to discuss or send in a pull request ;)


text:
package org.apache.hyracks.dataflow.common.comm.io;

import java.nio.ByteBuffer;

import org.apache.hyracks.api.comm.FrameConstants;
import org.apache.hyracks.api.comm.FrameHelper;
import org.apache.hyracks.api.comm.IFrame;
import org.apache.hyracks.api.comm.IFrameAppender;
import org.apache.hyracks.api.comm.IFrameWriter;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.dataflow.common.util.IntSerDeUtils;

public class AbstractFrameAppender implements IFrameAppender {
    protected IFrame frame;
    protected byte[] array; // cached the getBuffer().array to speed up byte array access a little

    protected int tupleCount;
    protected int tupleDataEndOffset;

    @Override
    public void reset(IFrame frame, boolean clear) throws HyracksDataException {
        this.frame = frame;
        if (clear) {
            this.frame.reset();
        }
        reset(getBuffer(), clear);
    }

    protected boolean hasEnoughSpace(int fieldCount, int tupleLength) {
        return tupleDataEndOffset + FrameHelper.calcSpaceInFrame(fieldCount, tupleLength)
                + tupleCount * FrameConstants.SIZE_LEN
                <= FrameHelper.getTupleCountOffset(frame.getFrameSize());
    }

    private void reset(ByteBuffer buffer, boolean clear) {
        array = buffer.array();
        if (clear) {
            IntSerDeUtils.putInt(array, FrameHelper.getTupleCountOffset(frame.getFrameSize()), 0);
            tupleCount = 0;
            tupleDataEndOffset = FrameConstants.TUPLE_START_OFFSET;
        } else {
            tupleCount = IntSerDeUtils.getInt(array, FrameHelper.getTupleCountOffset(frame.getFrameSize()));
            tupleDataEndOffset = tupleCount == 0 ?
                    FrameConstants.TUPLE_START_OFFSET :
                    IntSerDeUtils.getInt(array, FrameHelper.getTupleCountOffset(frame.getFrameSize())
                            - tupleCount * FrameConstants.SIZE_LEN);
        }
    }

    @Override
    public int getTupleCount() {
        return tupleCount;
    }

    @Override
    public ByteBuffer getBuffer() {
        return frame.getBuffer();
    }

    @Override
    public void flush(IFrameWriter outWriter, boolean clearFrame) throws HyracksDataException {
        getBuffer().clear();
        if (getTupleCount() > 0) {
            outWriter.nextFrame(getBuffer());
        }
        if (clearFrame) {
            frame.reset();
            reset(getBuffer(), true);
        }
    }

    protected boolean canHoldNewTuple(int fieldCount, int dataLength) throws HyracksDataException {
        if (hasEnoughSpace(fieldCount, dataLength)) {
            return true;
        }
        if (tupleCount == 0) {
            frame.ensureFrameSize(FrameHelper.calcAlignedFrameSizeToStore(fieldCount, dataLength, frame.getMinSize()));
            reset(frame.getBuffer(), true);
            return true;
        }
        return false;
    }

}


text:
Package.describe({
	name: 'tagt:ui-flextab',
	version: '0.1.0',
	// Brief, one-line summary of the package.
	summary: '',
	// URL to the Git repository containing the source code for this package.
	git: '',
	// By default, Meteor will default to using README.md for documentation.
	// To avoid submitting documentation, set this field to null.
	documentation: 'README.md'
});

Package.onUse(function(api) {
	api.use([
		'mongo',
		'ecmascript',
		'templating',
		'coffeescript',
		'underscore',
		'tagt:lib'
	]);

	api.use('tagt:ui');

	api.addFiles('flex-tab/flexTabBar.html', 'client');
	api.addFiles('flex-tab/tabs/membersList.html', 'client');
	api.addFiles('flex-tab/tabs/messageSearch.html', 'client');
	api.addFiles('flex-tab/tabs/uploadedFilesList.html', 'client');
	api.addFiles('flex-tab/tabs/userEdit.html', 'client');
	api.addFiles('flex-tab/tabs/userInfo.html', 'client');
	api.addFiles('flex-tab/tabs/membersListPage.html', 'client');

	api.addFiles('flex-tab/flexTabBar.coffee', 'client');
	api.addFiles('flex-tab/tabs/membersList.coffee', 'client');
	api.addFiles('flex-tab/tabs/messageSearch.coffee', 'client');
	api.addFiles('flex-tab/tabs/uploadedFilesList.coffee', 'client');
	api.addFiles('flex-tab/tabs/userEdit.coffee', 'client');
	api.addFiles('flex-tab/tabs/userInfo.coffee', 'client');
	api.addFiles('flex-tab/tabs/membersListPage.coffee', 'client');

});


text:
author: Aniket
layout: poetry
date: 2013-01-21 21:55 +0530
title: "Hope Springs Eternal"
category: poetry
---

The wind never dies

These thoughts never cease

Shades of black describe everything

I see people clad in white

Is this another aimless journey called life?

Walk with me

Let me take you by your hand

Stop living with yourself

Your life is worth living

Don't let it waste by

These thoughts will scar your memory

I am not just another somebody

Do i mean anything to you?

Even if you won't say it

But i still know

In the wake of determination

I take an oath

That I'll keep you safe

No matter what storms may come

And disasters dawn

I will not let you feel alone

As long as I'm there with you


text:
{% extends 'main.html' %}

{% block content %}

{% load staticfiles %}

Add New Payment Type

    <form action="{% url 'website:add_payment_type' %}" method="post">
      {% csrf_token %}
      {{ payment_type_form.as_p }}
      <input class="btn btn-success" type="submit" href="/user_payment_types" value="Add Payment Type" />
    </form>

{% endblock %}


text:
"""
    wechatpy.utils
    ~~~~~~~~~~~~~~~

    This module provides some useful utilities.

    :copyright: (c) 2014 by messense.
    :license: MIT, see LICENSE for more details.
"""
from __future__ import absolute_import, unicode_literals
import string
import random
import hashlib

try:
    '''Use simplejson if we can, fallback to json otherwise.'''
    import simplejson as json
except ImportError:
    import json  # NOQA

import six
import six.moves.urllib.parse as urlparse

class ObjectDict(dict):
    """Makes a dictionary behave like an object, with attribute-style access.
    """

    def __getattr__(self, key):
        if key in self:
            return self[key]
        return None

    def __setattr__(self, key, value):
        self[key] = value

class WeChatSigner(object):
    """WeChat data signer"""

    def __init__(self, delimiter=b''):
        self._data = []
        self._delimiter = to_binary(delimiter)

    def add_data(self, *args):
        """Add data to signer"""
        for data in args:
            self._data.append(to_binary(data))

    @property
    def signature(self):
        """Get data signature"""
        self._data.sort()
        str_to_sign = self._delimiter.join(self._data)
        return hashlib.sha1(str_to_sign).hexdigest()

def check_signature(token, signature, timestamp, nonce):
    """Check WeChat callback signature, raises InvalidSignatureException
    if check failed.

    :param token: WeChat callback token
    :param signature: WeChat callback signature sent by WeChat server
    :param timestamp: WeChat callback timestamp sent by WeChat server
    :param nonce: WeChat callback nonce sent by WeChat sever
    """
    signer = WeChatSigner()
    signer.add_data(token, timestamp, nonce)
    if signer.signature != signature:
        from wechatpy.exceptions import InvalidSignatureException

        raise InvalidSignatureException()

def to_text(value, encoding='utf-8'):
    """Convert value to unicode, default encoding is utf-8

    :param value: Value to be converted
    :param encoding: Desired encoding
    """
    if not value:
        return ''
    if isinstance(value, six.text_type):
        return value
    if isinstance(value, six.binary_type):
        return value.decode(encoding)
    return six.text_type(value)

def to_binary(value, encoding='utf-8'):
    """Convert value to binary string, default encoding is utf-8

    :param value: Value to be converted
    :param encoding: Desired encoding
    """
    if not value:
        return b''
    if isinstance(value, six.binary_type):
        return value
    if isinstance(value, six.text_type):
        return value.encode(encoding)
    return six.binary_type(value)

def timezone(zone):
    """Try to get timezone using pytz or python-dateutil

    :param zone: timezone str
    :return: timezone tzinfo or None
    """
    try:
        import pytz
        return pytz.timezone(zone)
    except ImportError:
        pass
    try:
        from dateutil.tz import gettz
        return gettz(zone)
    except ImportError:
        return None

def random_string(length=16):
    rule = string.ascii_letters + string.digits
    rand_list = random.sample(rule, length)
    return ''.join(rand_list)

def get_querystring(uri):
    """Get Querystring information from uri.

    :param uri: uri
    :return: querystring info or {}
    """
    parts = urlparse.urlsplit(uri)
    return urlparse.parse_qs(parts.query)

def byte2int(c):
    if six.PY2:
        return ord(c)
    return c


text:
using JK.Common.Specifications;
using Xunit;

namespace JK.Common.Tests.Specifications
{
    public class MaximumLengthSpecificationTests
    {
        [Theory]
        [InlineData("xxxxx", true)] // 5
        [InlineData("xxxxxxxxxx", true)] // 10
        [InlineData("xxxxxxxxxxxxxxx", false)] // 15
        public void IsSatisfiedBy(string input, bool expected)
        {
            var specification = new MaximumLengthSpecification(10);
            bool actual = specification.IsSatisfiedBy(input);
            Assert.Equal(expected, actual);
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0" xml:id="PrL-0389">
   <teiHeader>
      <fileDesc>
         <titleStmt>
            <title>Private Letter: 1879 June 14: to Hector</title>
            <author>
               <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/9614/">William Colenso</name>
            </author>
         </titleStmt>
         <publicationStmt>

         </publicationStmt>
         <sourceDesc>

MTG HB 18568.

         </sourceDesc>
      </fileDesc>
      <profileDesc>
         <correspDesc>

               <correspAction type="received">
                  <name type="person" key="http://wtap.vuw.ac.nz/eats/entity/33221/">Hector</name>
               </correspAction>
            </correspDesc>
         <creation xmlns:tei="http://www.tei-c.org/ns/1.0">
            <date when="1879-06-14">1879 June 14</date>
         </creation>
      </profileDesc>
   </teiHeader>
   <text>
      <front>

1879 June 14: to Hector<note xml:id="ftn3-12" place="foot" n="12"> MTG HB 18568.</note>

      </front>

Napier, June 14<hi rend="sup">th</hi>., 1879.

Dr. Hector,

My dear Sir,

I was pleased on receiving your telegram of the 3<hi rend="sup">rd</hi>. instant, informing me of the little box of "exhibits" having reached you "all right": <hi rend="italic">and</hi>, that you would write. Since then I have been on the look-out for a letter, but not greatly so, knowing how much your time is occupied with more important matters.

Before that I scribble anything of myself I should say, (to prevent if possible any more enquiries by Mr. Gore,) that our 80 Members are made up thus,—<hi rend="italic">viz. </hi>75 as printed in last Report (forwarded) and 5 since = 80. I fancy that ere long we may tot up 100!

I do not know when you will leave Wellington for the warmer clime, but I hope <hi rend="italic">before </hi>you do so you will not fail to return me my two "<hi rend="italic">Ruahine</hi>"<hi rend="italic"> </hi>Papers. I have just received more letters from abroad <hi rend="italic">re </hi>their private publication.

At our Meeting last Monday I read a Paper, (No. II of Series "Contributions to a better Knowledge of the Maori Races,") we had a good attendance, but, I fear, <hi rend="italic">I</hi> shall not do much more, in that way, for the Society. I have a score of things <hi rend="italic">to do </hi>(I may truly say) which have long been accumulating terribly, but I had set them aside to write for our Institute. Now, however, that I have so signally failed in the two <hi rend="italic">Ruahines </hi>I feel as if the spell were <hi rend="italic">broken</hi>; and so I told our <hi rend="italic">Council</hi> on Monday.—

I send you enclosed, a clipping from the "H.B. Herald" <hi rend="italic">re </hi>our Meeting,—the reporter being present. Mr. Peppercorne, our Municipal Engineer, has written a Paper for our next month's meeting, "On the influence of Forests on Climate and Rainfall,"—which I have promised to read for him.—

I noticed a few printer's errors in my 2–3 Papers printed in vol. xi (the <hi rend="italic">one </hi>copy sent for our Library by Mr. Gore)—but such will always be the case, I fear, in <hi rend="italic">Maori </hi>words, unless <hi rend="italic">I correct the sheet</hi>: and surely this can easily be arranged?

I am going to ask you a favour, (which is both <hi rend="italic">within </hi>your power & not <hi rend="italic">very </hi>hard or troublesome,) <hi rend="italic">viz.</hi> to get your Mr. Gore to write his name some 50 times on a sheet of paper, so that I may cut them off separately and paste on the coverings of vol. xi. when I send them out by post: our Post Master says, this will do. We, <hi rend="italic">here</hi>, have no one now privileged to frank whom I can ask; Locke did for me last year. But (as I said to you last summer) a single line from the Post Master General to the 5–6 offices where your Branch Societies are,—to allow of the free postage, or <hi rend="italic">mail carriage</hi>, of your publications, would be better still, and save all the bother.

Where can I apply for copies of the various works published by your Department? <hi rend="italic">e.g. </hi>Fishes, Birds, Molluscs, &c.,—to <hi rend="italic">buy them</hi>, of course.—

                             Believe me ever, &c.,

                                             Wm. Colenso.

   </text>
</TEI>


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

namespace Gizeta.KCV.ManualCounter.Utils
{
    public static class EnumHelper
    {
        public static T GetEnumAttribute<T>(this Enum source) where T : Attribute
        {
            Type type = source.GetType();
            string sourceName = Enum.GetName(type, source);
            FieldInfo field = type.GetField(sourceName);
            object[] attributes = field.GetCustomAttributes(typeof(T), false);
            foreach (var o in attributes)
            {
                if (o is T)
                    return (T)o;
            }
            return null;
        }

        public static string GetDescription(this Enum source)
        {
            var desc = source.GetEnumAttribute<DescriptionAttribute>();
            if (desc == null)
                return null;
            return desc.Description;
        }
    }
}


text: NSString *formatInt(int amount);


text:
        <?php foreach ($items as $item): ?>

                    <img class="card-img-top" src="<?= base_url() ?>assets/uploads/<?php echo $item->img; ?>" height="236" alt="Card image cap">

<?php echo $item->status; ?>

Location : <?php echo $item->location; ?>

Item Resolved At : <?php echo $item->date; ?>

        <?php endforeach; ?>