text:
import React, {PropTypes} from 'react';
import {View, Text, TextInput, Image, ListView, TouchableHighlight, StyleSheet} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import Component from '../PureComponent';

export default class MatchingContacts extends Component{
    render(){
        const { isSearching, filteredContacts } = this.props;

        if(!isSearching){
            return null;
        }
        let contactsDS = new ListView.DataSource({
            rowHasChanged: (r1, r2) => r1 !== r2 });
        contactsDS = contactsDS.cloneWithRows(filteredContacts);
        return(
            <View style={styles.listContainer}>
                <ListView
                    dataSource={contactsDS}
                    renderRow={(contact, sectionID, rowID) => this._renderMatchingContactItem(contact, sectionID, rowID)}/>
            </View>
        );
    }

    _renderMatchingContactItem(contact, sectionID, rowID) {
        let phoneLabel = contact.phoneLabel? contact.phoneLabel: '';
        return (
            <TouchableHighlight onPress={()=> this.props.selectContact(contact)} key={contact.phoneNumber}>
                <View style={styles.contactItemContainer}>
                    <View style={styles.horizontalNoWrap}>
                        <Text style={[styles.title]}>{contact.displayName}</Text>
                    </View>
                    <Text style={[styles.phoneNumber]}>{phoneLabel} {contact.phoneNumber}</Text>
                    <View style={styles.contactDivider}/>
                </View>
            </TouchableHighlight>
        );
    }
}

const styles = StyleSheet.create({
    listContainer: {
        flex: 1,
    },
    horizontalNoWrap:{
        flexDirection : 'row',
        flexWrap      : 'nowrap'
    },
    title: {
        fontSize: 14,
        color: '#656565',
        fontWeight: 'bold',
        flex: 1
    },
    contactItemContainer: {
        margin: 5,
        paddingLeft: 20
    },
    contactDivider:{
        margin: 10,
        height: 1,
        backgroundColor: '#dddddd'
    },
    phoneNumber:{
        color: '#9c9393',
        fontSize: 12,
        fontStyle: 'italic',
    }
});
MatchingContacts.propTypes = {
    isSearching: PropTypes.bool.isRequired,
    selectContact: PropTypes.func.isRequired
};


text:
import { DOMNodeType } from "../../dom";
import { SourceLocation2 } from "aerial-sandbox2";
import {
  Struct,
  Bounds,
  Point,
  weakMemo,
  traverseObject,
  createStructFactory,
} from "aerial-common2";

/**
 * Constants
 */

export const DOM_TEXT_NODE              = "DOM_TEXT_NODE";
export const DOM_ELEMENT                = "DOM_ELEMENT";
export const DOM_DOCUMENT               = "DOM_DOCUMENT";
export const DOM_COMMENT                = "DOM_COMMENT";
export const SYTNTHETIC_BROWSER_WINDOW  = "SYNTHETIC_BROWSER_WINDOW";
export const SYNTHETIC_BROWSER          = "SYNTHETIC_BROWSER";

const DEFAULT_SYNTHETIC_WINDOW_BOX: Bounds = {
  left: 0,
  top: 0,

  // small screen size
  right: 800,
  bottom: 600
};

export type SyntheticDOMNode2 = {
  nodeType: DOMNodeType;
  nodeName: string;
  $source: SourceLocation2;
  childNodes: SyntheticDOMNode2[];
} & Struct;

export type SyntheticDOMValueNode2 = {
  nodeValue: string;
} & SyntheticDOMNode2;

export type SyntheticDOMComment2 = {
  nodeValue: string;
  nodeName: "#comment";
} & SyntheticDOMValueNode2;

export type SyntheticDOMTextNode2 = {
  nodeValue: string;
  nodeName: "#text";
} & SyntheticDOMValueNode2;

export type SyntheticCSSStyle2 = {

} & Struct;

export type SyntheticDOMElementAttributes2 = {
  [identifier: string]: string
} & Struct;

export type SyntheticDOMElement2 = {
  nodeName: string;
  attributes: SyntheticDOMElementAttributes2;
  computedStyle: SyntheticCSSStyle2;
} & SyntheticDOMNode2;

export type SyntheticDOMDocument2 = {
  nodeName: "#document";
} & SyntheticDOMNode2;

export type SyntheticBrowserWindow2 = {
  mount: HTMLElement;
  document: SyntheticDOMDocument2;
  location: string;
  title: string;
  bounds: Bounds;
  allComputedBounds: {
    [identifier: string]: Bounds;
  };
  allComputedStyles: {
    [identifier: string]: CSSStyleDeclaration
  }
} & Struct;

export type SyntheticBrowserRenderer2 = {

} & Struct;

export type SyntheticBrowserDOMRenderer2 = {
  syntheticBrowserWindowId: string;
  nativeDocumentElenent: HTMLElement;
} & SyntheticBrowserRenderer2;

export type SyntheticBrowser2 = {
  windows: SyntheticBrowserWindow2[]
} & Struct;

export const isSyntheticDOMNode = (value) => value && value.nodeType != null;
/**
 * Utilities
 */

export const createSyntheticBrowser2 = createStructFactory<SyntheticBrowser2>(SYNTHETIC_BROWSER, {
  windows: []
});

export const createSyntheticBrowserWindow2 = createStructFactory<SyntheticBrowserWindow2>(SYTNTHETIC_BROWSER_WINDOW, {
  allComputedStyles: {},
  allComputedBounds: {},
  bounds: DEFAULT_SYNTHETIC_WINDOW_BOX
});

export const getSyntheticBrowserWindow = (root: any, id: string): SyntheticBrowserWindow2 => {
  return getValueById(root, id);
};

export const getSyntheticBrowser = (root: any, id: string): SyntheticBrowser2 => {
  return getValueById(root, id);
};

export const findSyntheticDOMNodes = weakMemo((root: any, filter: (node: SyntheticDOMNode2) => boolean): SyntheticDOMNode2[] => {
  const found: SyntheticDOMNode2[] = [];
  traverseObject(root, (item: any) => {
    if (isSyntheticDOMNode(item) && filter(item)) {
      found.push(item);
    }
  });
  return found;
});

export const getAllSyntheticDOMNodes = weakMemo((root: any) => findSyntheticDOMNodes(root, () => true));
export const getAllSyntheticDOMNodesAsIdMap = weakMemo((root: any): { [identifier: string]: SyntheticDOMNode2 } => {
  const allNodes = getAllSyntheticDOMNodes(root);
  const map = {};
  for (const node of allNodes) {
    map[node.$id] = node;
  }
  return map;
});

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Numbers\Users\Users\Form\Form;
class Overrides extends \Object\Form\Wrapper\Base {
	public $form_link = 'um_groups';
	public $module_code = 'UM';
	public $title = 'U/M Form Overrides Form';
	public $options = [
		'segment' => self::SEGMENT_FORM,
		'actions' => [
			'refresh' => true,
			'back' => true,
			'new' => true,
			'import' => true
		]
	];
	public $containers = [
		'top' => ['default_row_type' => 'grid', 'order' => 100],
		'buttons' => ['default_row_type' => 'grid', 'order' => 900]
	];
	public $rows = [];
	public $elements = [
		'top' => [
			'um_formoverride_id' => [
				'um_formoverride_id' => ['order' => 1, 'row_order' => 100, 'label_name' => 'Override #', 'domain' => 'group_id_sequence', 'percent' => 95, 'navigation' => true],
				'um_formoverride_inactive' => ['order' => 2, 'label_name' => 'Inactive', 'type' => 'boolean', 'percent' => 5]
			],
			'um_formoverride_name' => [
				'um_formoverride_name' => ['order' => 1, 'row_order' => 200, 'label_name' => 'Name', 'domain' => 'name', 'percent' => 100, 'required' => true],
			],
			'um_formoverride_module_code' => [
				'um_formoverride_module_code' => ['order' => 1, 'row_order' => 300, 'label_name' => 'Module Code', 'domain' => 'module_code', 'null' => true, 'percent' => 50, 'required' => true, 'method' => 'select', 'options_model' => '\Numbers\Backend\System\Modules\Model\Modules', 'onchange' => 'this.form.submit();'],
				'um_formoverride_module_id' => ['order' => 2, 'label_name' => 'Module #', 'domain' => 'module_id', 'null' => true, 'percent' => 50, 'required' => true, 'method' => 'select', 'options_model' => '\Numbers\Tenants\Tenants\Model\Modules', 'options_depends' => ['tm_module_module_code' => 'um_formoverride_module_code'], 'onchange' => 'this.form.submit();'],
			],
			'um_formoverride_form_code' => [
				'um_formoverride_form_code' => ['order' => 1, 'row_order' => 400, 'label_name' => 'Form', 'domain' => 'code', 'null' => true, 'required' => true, 'percent' => 50, 'method' => 'select', 'options_model' => '\Numbers\Backend\System\Modules\Model\Forms', 'options_depends' => ['sm_form_module_code' => 'um_formoverride_module_code'], 'onchange' => 'this.form.submit();'],
				'um_formoverride_form_field_code' => ['order' => 2, 'label_name' => 'Field', 'domain' => 'code', 'null' => true, 'required' => true, 'percent' => 50, 'method' => 'select', 'tree' => true, 'options_model' => '\Numbers\Backend\System\Modules\Model\Form\Fields::optionsGrouped', 'options_depends' => ['sm_frmfield_form_code' => 'um_formoverride_form_code'], 'onchange' => 'this.form.submit();'],
			],
			'um_formoverride_action' => [
				'um_formoverride_action' => ['order' => 1, 'row_order' => 500, 'label_name' => 'Action', 'domain' => 'type_id', 'null' => true, 'required' => true, 'percent' => 100, 'method' => 'select', 'options_model' => '\Numbers\Users\Users\Model\Form\ActionTypes'],
			],
			'um_formoverride_role_id' => [
				'um_formoverride_role_id' => ['order' => 1, 'row_order' => 600, 'label_name' => 'Role', 'domain' => 'role_id', 'null' => true, 'required' => 'c', 'percent' => 50, 'method' => 'select', 'options_model' => '\Numbers\Users\Users\Model\Roles'],
				'um_formoverride_role_weight' => ['order' => 2, 'label_name' => 'Maximum Role Weight', 'domain' => 'weight', 'null' => true, 'required' => 'c', 'percent' => 50],
			]
		],
		'buttons' => [
			self::BUTTONS => self::BUTTONS_DATA_GROUP
		]
	];
	public $collection = [
		'name' => 'Overrides',
		'model' => '\Numbers\Users\Users\Model\Form\Overrides'
	];

	public function validate(& $form) {
		if (empty($form->values['um_formoverride_role_id']) && empty($form->values['um_formoverride_role_weight'])) {
			$form->error(DANGER, 'Role or Maximum Role Weight is reqired!', 'um_formoverride_role_id');
			$form->error(DANGER, 'Role or Maximum Role Weight is reqired!', 'um_formoverride_role_weight');
		}
	}

	public function processOptionsModels(& $form, $field_name, $details_key, $details_parent_key, & $where) {
		if ($field_name == 'um_formoverride_role_id') {
			$where['selected_organizations'] = \User::get('organizations');
		}
	}
}


text:
package com.josephshanak.musicgenerator.util;

/**
 * Created by Joe on 2/26/2017.
 * @author Joe
 * @history 2/26/2017 - Created
 */
public interface Copyable<T> {
    T copy();
}


text:
package master

import (
	"sync"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/client"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/registry/pod"

	"github.com/golang/glog"
)

// PodCache contains both a cache of container information, as well as the mechanism for keeping
// that cache up to date.
type PodCache struct {
	containerInfo client.PodInfoGetter
	pods          pod.Registry
	// This is a map of pod id to a map of container name to the
	podInfo map[string]api.PodInfo
	podLock sync.Mutex
}

// NewPodCache returns a new PodCache which watches container information registered in the given PodRegistry.
func NewPodCache(info client.PodInfoGetter, pods pod.Registry) *PodCache {
	return &PodCache{
		containerInfo: info,
		pods:          pods,
		podInfo:       map[string]api.PodInfo{},
	}
}

// makePodCacheKey constructs a key for use in a map to address a pod with specified namespace and id
func makePodCacheKey(podNamespace, podID string) string {
	return podNamespace + "." + podID
}

// GetPodInfo implements the PodInfoGetter.GetPodInfo.
// The returned value should be treated as read-only.
// TODO: Remove the host from this call, it's totally unnecessary.
func (p *PodCache) GetPodInfo(host, podNamespace, podID string) (api.PodInfo, error) {
	p.podLock.Lock()
	defer p.podLock.Unlock()
	value, ok := p.podInfo[makePodCacheKey(podNamespace, podID)]
	if !ok {
		return nil, client.ErrPodInfoNotAvailable
	}
	return value, nil
}

func (p *PodCache) updatePodInfo(host, podNamespace, podID string) error {
	info, err := p.containerInfo.GetPodInfo(host, podNamespace, podID)
	if err != nil {
		return err
	}
	p.podLock.Lock()
	defer p.podLock.Unlock()
	p.podInfo[makePodCacheKey(podNamespace, podID)] = info
	return nil
}

// UpdateAllContainers updates information about all containers.  Either called by Loop() below, or one-off.
func (p *PodCache) UpdateAllContainers() {
	ctx := api.NewContext()
	pods, err := p.pods.ListPods(ctx, labels.Everything())
	if err != nil {
		glog.Errorf("Error synchronizing container list: %v", err)
		return
	}
	for _, pod := range pods.Items {
		if pod.CurrentState.Host == "" {
			continue
		}
		err := p.updatePodInfo(pod.CurrentState.Host, pod.Namespace, pod.Name)
		if err != nil && err != client.ErrPodInfoNotAvailable {
			glog.Errorf("Error synchronizing container: %v", err)
		}
	}
}


text:
import hmac
import random
import string
import hashlib
import pymongo
import time
from pprint import pprint
import datetime

mClasses = {
    "monty": {
        "vars": ["prize_door", "contestant_door", "monty_door"],
        "bettingVar": "prize_door",
        "domain": ["A", "B", "C"]
    },
    "banking": {
        "vars": ["bank_1", "bank_2"],
        "bettingVar": "bank_2",
        "domain": ['H', 'L']
    },
    "demo": {
        "vars": ["interest_rate", "unemployment", "production", "exports"],
        "bettingVar": "interest_rate",
        "domain": ['H', 'L']
    },
    "complex": {
        "vars": ["interest_rate", "bank_income", "general_motors", "consumer_spending"],
        "bettingVar": "interest_rate",
        "domain": ['H', 'L']
    },
    "simple": {
        "vars": ["interest_rate", "bank_income", "general_motors"],
        "bettingVar": "interest_rate",
        "domain": ['H', 'L']
    }
}

currMClass = "simple"
# The Data Access Object handles all interactions with the Data collection.

class mClassDAO:
    def __init__(self, db):
        self.mClass = db.mClass
        self.next_treatment = 0
        self.treatments = [
            #('simple', 1000),
                ('demo', 1000),
                ('complex', 1000),
            #('simple', 2000),
                ('demo', 2000),
                ('complex', 2000)
        ]
        # creates a new user in the users collection
        lastUserAddedList = list(self.mClass.find().sort('timeAdded', -1).limit(1))
        if not lastUserAddedList:
            self.next_treatment = 0
        else:
            self.next_treatment = lastUserAddedList[0]['treatmentNum']

        #self.min_group_users = 8
        #mClass, points = self.get_group_treatment(self.next_group)
        #treatment_ndx = self.treatments.index((mClass, points))
        #self.next_treatment = treatment_ndx + 1

    #def new_group(self):
    #    self.next_group += 1
    #    self.assign_treatment(self.next_group)
    #    return self.next_group
    def get_treatment_from_num(self, treatmentNum):
        return self.treatments[treatmentNum]

    def empty_data(self):
        self.mClass.remove({})

    def assign_treatment(self, user_id):
        assignedTreatmentNum = self.next_treatment
        self.next_treatment += 1
        if self.next_treatment >= len(self.treatments):
            self.next_treatment = 0
        mClass, points = self.treatments[assignedTreatmentNum]
        self.mClass.insert({
            'user' : user_id,
            'mClass': mClass,
            'points': points,
            'timeAdded': datetime.datetime.now(),
            'treatmentNum': assignedTreatmentNum,
        })
        return assignedTreatmentNum, mClass, points

    #def get_num_users_in_group(self, group_id):
    #    num_users_in_group = self.user_groups.find({
    #        'group': group_id
    #    }).count()
    #    return num_users_in_group

    def assign_treatment_if_not_already(self, user_id):
        prevTreatment = self.mClass.find_one({'user': user_id})
        if not prevTreatment:
            return self.assign_treatment(user_id)
        else:
            return prevTreatment['treatmentNum'], prevTreatment['mClass'], prevTreatment['points']

    #def assign_group_if_not_already(self, user_id):
    #    prevGroup = self.user_groups.find_one({'user': user_id})
    #    if not prevGroup:
    #        return self.assign_group(user_id)
    #    else:
    #        return prevGroup['group']

    #def assign_group(self, user_id):
    #    total_num_users = self.user_groups.find().count()
    #    if total_num_users < 200:
    #        num_users_in_next_group = self.get_num_users_in_group(self.next_group)
    #        if num_users_in_next_group >= 8:
    #            group_id = self.new_group()
    #        else:
    #            group_id = self.next_group
    #    else:
    #        group_id = self.get_min_usr_grp()

    #    self.user_groups.insert({
    #        'user': user_id,
    #        'group': group_id
    #    })
    #    return group_id

    #def get_num_groups(self):
    #    return self.group_treatments.find().count()

    #def get_min_usr_grp(self):
    #    for group_num in range(self.get_num_groups()):
    #        num_group_users = self.get_num_users_in_group(group_num)
    #        if num_group_users <= self.min_group_users:
    #            return group_num
    #    self.min_group_users += 1
    #    return self.get_min_usr_grp()

    #def get_group_mClass(self, group_num):
    #    group_entry = self.group_treatments.find_one({'group': group_num})
    #    if group_entry == None:
    #        return -1
    #    else:
    #        return group_entry['mClass']

    def clear(self):
        self.mClass.remove()

    def reset(self):
        self.mClass.remove()
        self.next_treatment = 0

    def show(self):
        user_treatments = self.mClass.find()
        print "user_treatments:"
        pprint(list(user_treatments))
        print

    #def get_user_treatment(self, user_id):
    #    user_group = self.get_user_group(user_id)
    #    return self.get_group_treatment(user_group)

    #def get_group_treatment(self, group_id):
    #    group_entry = self.group_treatments.find_one({'group': group_id})
    #    if group_entry:
    #        return group_entry['mClass'], group_entry['points']
    #    else:
    #        raise ValueError("group id ", group_id, " not found")

    #def get_user_group(self, user_id):
    #    user_entry = self.user_groups.find_one({'user': user_id})
    #    if user_entry:
    #        return user_entry['group']
    #    else:
    #        raise ValueError ("group id not found")


text:
Simple portfolio page based on the start bootstrap template Agency, licensed under Apache 2.0.

# [Start Bootstrap](http://startbootstrap.com/) - [Agency](http://startbootstrap.com/template-overviews/agency/)

[Agency](http://startbootstrap.com/template-overviews/agency/) is a one page agency portfolio theme for [Bootstrap](http://getbootstrap.com/) created by [Start Bootstrap](http://startbootstrap.com/). This theme features several content sections, a responsive portfolio grid with hover effects, full page portfolio item modals, a responsive timeline, and a working PHP contact form.

## Copyright and License of Start bootstrap template

Copyright 2013-2015 Iron Summit Media Strategies, LLC. Code released under the [Apache 2.0](https://github.com/IronSummitMedia/startbootstrap-agency/blob/gh-pages/LICENSE) license.


text: int main(void) { printf("The answer is: %d\n", libA_func()); }


text:
use strict;
use warnings;
use Nmap::Parser;
use Term::ANSIColor;
use Getopt::Std;

my $usage = "nmap_self.pl [-f filename]";

sub usage {
	print $usage,$/,"\t",$_[0],$/;
	exit 1;
}

#get options from commandline
my $opts = {};
getopts("f:", $opts) or &usage('Bad Options');
my $filename = $opts->{f} || "config.csv";

#checks if file exists
if(defined $filename)
{
	#opens file
	open(CONFIGFILE, $filename) or die "Could not open file";
	#goes through file line by line
	while(<CONFIGFILE>)
	{
		chomp;
		#splits file into array
		my @array=split(/,/,$_);
		my $arraysize=@array;
		#first element in file is host address
		my $host=$array[0];
		my @acceptable;
		my $count=0;
		#all other elements are ports that are allowed to be open
		for ($count = 0; $count < $arraysize-1; $count++)
		{
			$acceptable[$count]=$array[$count+1];
		}
		#creates new nmap object
		my $np = new Nmap::Parser;

		#location of nmap on system
		my $nmap_exe = '/usr/local/bin/nmap';
		#ip address of host to scan
		my $ipaddr = $host;
		#runs scan, with specific options
		$np->parsescan($nmap_exe, '-sS', $ipaddr);

		#information about the scan
		print "Scan Information:\n";
		my $si = $np->get_session();

		print "\tNumber of services scanned: ".$si->numservices()."\n";

		#information about specific host
		print "Hosts scanned:\n";
		my $host_obj = $np->get_host($ipaddr);

		#print color 'red';
		print "\tHostname: ".$host_obj->hostname()."\n";
		print "\tStatus: ".$host_obj->status()."\n";
		print "\tIP Address:".$host_obj->addr()."\n";
		#print "\tMAC Address:".$host_obj->mac_addr()."\n";
		print "\tOpen Ports:\n";
		#creates array out of open ports
		my $teststring = join(',',$host_obj->tcp_ports('open'));
		my @testarray = split(/,/, $teststring);

		#print "Test Array: ".@testarray."\n";
		#print "Acceptable Array: ".@acceptable."\n";
		#compares array of open ports to acceptable open ports
		foreach my $i(@testarray)
		{
			foreach my $j(@acceptable)
			{
				#if port is suppose to be open prints it in green
				if($j eq $i)
				{
					print color 'green';
					print "\t\t".$i."\n";
					shift(@acceptable);
					last;
				}
				#if port is not suppose to be open prints in red
				elsif($j ne $i)
				{
					print color 'red';
					print "\t\t".$i."\n";
					last;
				}
			}
		}
		if(length(@acceptable) > 0)
		{
			print color 'yellow';
			foreach my $k(@acceptable)
			{
				print "\t\t".$k."\n";
			}
		}
		#Destroys nmap object
		$np->purge();
		print color 'reset';
	}
}


text:
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
 * The MIT License
 *
 * Copyright 2015 Eric VILLARD <dev@eviweb.fr>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @package     netbeans\phpunit\support
 * @author      Eric VILLARD <dev@eviweb.fr>
 * @copyright   (c) 2015 Eric VILLARD <dev@eviweb.fr>
 * @license     http://opensource.org/licenses/MIT MIT License
 */

namespace netbeans\phpunit\support;

use netbeans\phpunit\support\exceptions\FileNotFoundException;
use PHPUnit\TextUI\TestSuiteMapper;
use PHPUnit\TextUI\XmlConfiguration\Loader;

/**
 * TestSuiteProvider
 *
 * @package     netbeans\phpunit\support
 * @author      Eric VILLARD <dev@eviweb.fr>
 * @copyright   (c) 2015 Eric VILLARD <dev@eviweb.fr>
 * @license     http://opensource.org/licenses/MIT MIT License
 */
final class TestSuiteProvider
{

    /**
     * phpunit configuration file
     *
     * @var string
     */
    private static $file;

    /**
     * constructor
     */
    private function __construct()
    {

    }

    /**
     * set the phpunit configuration file
     *
     * @param string $file the path or filename of the phunit configuration file
     */
    public static function setConfigurationFile($file)
    {
        static::$file = $file;
    }

    /**
     * get the phpunit test suite instance
     *
     * @return PHPUnit\Framework\TestSuite returns the phpunit test suite instance
     * @throws FileNotFoundException       if the file is not found
     */
    public static function suite()
    {
        $file = static::checkConfigurationFile(
                static::getConfigurationFile()
        );

        return (new TestSuiteMapper)->map(((new Loader())->load($file)->testSuite()), '');
    }

    /**
     * get the phpunit configuration file
     *
     * @return string
     */
    private static function getConfigurationFile()
    {
        static::$file = isset(static::$file) ? static::$file : getcwd() . DIRECTORY_SEPARATOR . 'phpunit.xml';

        return static::$file;
    }

    /**
     * check the given file
     *
     * @param  string                $file file to check
     * @return string                returns the file if it is valid
     * @throws FileNotFoundException if the file is not found
     */
    private static function checkConfigurationFile($file)
    {
        if (!file_exists($file)) {
            throw new FileNotFoundException("The requested phpunit configuration was not found at $file");
        }

        return $file;
    }

}


text: [iOS Swift3] VIP Clean Architecture + RDP + Tests


text:
package route

import (
	"context"
	"encoding/json"
	"fmt"
	"time"

	"github.com/google/go-cmp/cmp"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"golang.org/x/sync/errgroup"

	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/equality"
	apierrs "k8s.io/apimachinery/pkg/api/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/util/sets"

	"knative.dev/networking/pkg/apis/networking"
	netv1alpha1 "knative.dev/networking/pkg/apis/networking/v1alpha1"
	"knative.dev/pkg/controller"
	"knative.dev/pkg/logging"
	"knative.dev/serving/pkg/apis/serving"
	v1 "knative.dev/serving/pkg/apis/serving/v1"
	"knative.dev/serving/pkg/reconciler/route/config"
	"knative.dev/serving/pkg/reconciler/route/resources"
	"knative.dev/serving/pkg/reconciler/route/resources/names"
	"knative.dev/serving/pkg/reconciler/route/traffic"
)

func (c *Reconciler) reconcileIngress(
	ctx context.Context, r *v1.Route, tc *traffic.Config,
	tls []netv1alpha1.IngressTLS,
	ingressClass string,
	acmeChallenges ...netv1alpha1.HTTP01Challenge,
) (*netv1alpha1.Ingress, *traffic.Rollout, error) {
	recorder := controller.GetEventRecorder(ctx)
	var effectiveRO *traffic.Rollout

	ingress, err := c.ingressLister.Ingresses(r.Namespace).Get(names.Ingress(r))
	if apierrs.IsNotFound(err) {
		desired, err := resources.MakeIngress(ctx, r, tc, tls, ingressClass, acmeChallenges...)
		if err != nil {
			return nil, nil, err
		}
		ingress, err = c.netclient.NetworkingV1alpha1().Ingresses(desired.Namespace).Create(ctx, desired, metav1.CreateOptions{})
		if err != nil {
			recorder.Eventf(r, corev1.EventTypeWarning, "CreationFailed", "Failed to create Ingress: %v", err)
			return nil, nil, fmt.Errorf("failed to create Ingress: %w", err)
		}

		recorder.Eventf(r, corev1.EventTypeNormal, "Created", "Created Ingress %q", ingress.GetName())
		return ingress, tc.BuildRollout(), nil
	} else if err != nil {
		return nil, nil, err
	} else {
		// Ingress exists. We need to compute the rollout spec diff.
		effectiveRO = c.reconcileRollout(ctx, r, tc, ingress)
		desired, err := resources.MakeIngressWithRollout(ctx, r, tc, effectiveRO,
			tls, ingressClass, acmeChallenges...)
		if err != nil {
			return nil, nil, err
		}

		if !equality.Semantic.DeepEqual(ingress.Spec, desired.Spec) ||
			!equality.Semantic.DeepEqual(ingress.Annotations, desired.Annotations) ||
			!equality.Semantic.DeepEqual(ingress.Labels, desired.Labels) {

			// It is notable that one reason for differences here may be defaulting.
			// When that is the case, the Update will end up being a nop because the
			// webhook will bring them into alignment and no new reconciliation will occur.
			// Also, compare annotation and label in case ingress.Class or parent route's labels
			// is updated.

			// Don't modify the informers copy.
			origin := ingress.DeepCopy()
			origin.Spec = desired.Spec
			origin.Annotations = desired.Annotations
			origin.Labels = desired.Labels

			updated, err := c.netclient.NetworkingV1alpha1().Ingresses(origin.Namespace).Update(
				ctx, origin, metav1.UpdateOptions{})
			if err != nil {
				return nil, nil, fmt.Errorf("failed to update Ingress: %w", err)
			}
			return updated, effectiveRO, nil
		}
	}

	return ingress, effectiveRO, err
}

func (c *Reconciler) deleteOrphanedServices(ctx context.Context, r *v1.Route, activeServices []resources.ServicePair) error {
	ns := r.Namespace

	active := make(sets.String, len(activeServices))

	for _, service := range activeServices {
		active.Insert(service.Service.Name)
	}

	routeLabelSelector := labels.SelectorFromSet(labels.Set{serving.RouteLabelKey: r.Name})
	allServices, err := c.serviceLister.Services(ns).List(routeLabelSelector)

	if err != nil {
		return fmt.Errorf("failed to fetch existing services: %w", err)
	}

	for _, service := range allServices {
		if active.Has(service.Name) {
			continue
		}

		if err := c.kubeclient.CoreV1().Services(ns).Delete(ctx, service.Name, metav1.DeleteOptions{}); err != nil {
			return fmt.Errorf("failed to delete Service: %w", err)
		}

		// Delete the endpoint if it exists
		_, err := c.endpointsLister.Endpoints(ns).Get(service.Name)
		if apierrs.IsNotFound(err) {
			continue
		} else if err != nil {
			return fmt.Errorf("failed to list endpoint: %w", err)
		}

		if err := c.kubeclient.CoreV1().Endpoints(ns).Delete(ctx, service.Name, metav1.DeleteOptions{}); err != nil {
			return fmt.Errorf("failed to delete Endpoints: %w", err)
		}
	}

	return nil
}

func (c *Reconciler) reconcilePlaceholderServices(ctx context.Context, route *v1.Route, targets map[string]traffic.RevisionTargets) ([]resources.ServicePair, error) {
	logger := logging.FromContext(ctx)
	recorder := controller.GetEventRecorder(ctx)
	ns := route.Namespace
	services := make([]resources.ServicePair, 0, len(targets))
	names := make(sets.String, len(targets))

	// Note: this is done in order for the tests to be
	// deterministic since they assert creations in order
	for name := range targets {
		names.Insert(name)
	}

	for _, name := range names.List() {
		desiredService, err := resources.MakeK8sPlaceholderService(ctx, route, name)
		if err != nil {
			return nil, fmt.Errorf("failed to construct placeholder k8s service: %w", err)
		}

		service, err := c.serviceLister.Services(ns).Get(desiredService.Name)
		if apierrs.IsNotFound(err) {
			// Doesn't exist, create it.
			service, err = c.kubeclient.CoreV1().Services(ns).Create(ctx, desiredService, metav1.CreateOptions{})
			if err != nil {
				recorder.Eventf(route, corev1.EventTypeWarning, "CreationFailed",
					"Failed to create placeholder service %q: %v", desiredService.Name, err)
				return nil, fmt.Errorf("failed to create placeholder service: %w", err)
			}
			logger.Info("Created service ", desiredService.Name)
			recorder.Eventf(route, corev1.EventTypeNormal, "Created", "Created placeholder service %q", desiredService.Name)
		} else if err != nil {
			return nil, err
		} else if !metav1.IsControlledBy(service, route) {
			// Surface an error in the route's status, and return an error.
			route.Status.MarkServiceNotOwned(desiredService.Name)
			return nil, fmt.Errorf("route: %q does not own Service: %q", route.Name, desiredService.Name)
		}

		// Check if we have endpoints for this service
		endpoints, err := c.endpointsLister.Endpoints(ns).Get(desiredService.Name)
		if apierrs.IsNotFound(err) {
			// noop
		} else if err != nil {
			return nil, err
		} else if !metav1.IsControlledBy(endpoints, route) {
			// Surface an error in the route's status, and return an error.
			route.Status.MarkEndpointNotOwned(desiredService.Name)
			return nil, fmt.Errorf("route: %q does not own Endpoints: %q", route.Name, desiredService.Name)
		}

		services = append(services, resources.ServicePair{
			Service:   service,
			Endpoints: endpoints,
			Tag:       name,
		})
	}

	// Delete any current services that was no longer desired.
	if err := c.deleteOrphanedServices(ctx, route, services); err != nil {
		return nil, err
	}

	// TODO(mattmoor): This is where we'd look at the state of the Service and
	// reflect any necessary state into the Route.
	return services, nil
}

func (c *Reconciler) updatePlaceholderServices(ctx context.Context, route *v1.Route, pairs []resources.ServicePair, ingress *netv1alpha1.Ingress) error {
	logger := logging.FromContext(ctx)
	ns := route.Namespace

	eg, egCtx := errgroup.WithContext(ctx)
	for _, from := range pairs {
		from := from
		eg.Go(func() error {
			to, err := resources.MakeK8sService(egCtx, route, from.Tag, ingress, resources.IsClusterLocalService(from.Service))
			if err != nil {
				// Loadbalancer not ready, no need to update.
				logger.Warnw("Failed to update k8s service", zap.Error(err))
				return nil
			}

			canUpdate := false

			if from.Spec.Type != to.Spec.Type {
				switch from.Spec.Type {
				// Transitions from ExternalName to any type should work
				case corev1.ServiceTypeExternalName:
					canUpdate = true
				default:
					// Transitions from ClusterIP to ExternalName Fail
					// See: https://github.com/kubernetes/kubernetes/issues/104329
				}
			} else if from.Spec.Type == corev1.ServiceTypeClusterIP {
				if from.Spec.ClusterIP == to.Spec.ClusterIP {
					canUpdate = true
				} else if from.Spec.ClusterIP != corev1.ClusterIPNone && to.Spec.ClusterIP == "" {
					// Copy over the cluster IP
					to.Spec.ClusterIP = from.Spec.ClusterIP
					canUpdate = true
				}
				// else:
				//   clusterIPs are immutable thus any transition requires a recreate
				//   ie. "None" <=> "" (blank - request an IP)

			} else /* types are the same and not clusterIP */ {
				canUpdate = true
			}

			if canUpdate {
				// Make sure that the service has the proper specification.
				if !equality.Semantic.DeepEqual(from.Service.Spec, to.Service.Spec) {
					// Don't modify the informers copy.
					existing := from.Service.DeepCopy()
					existing.Spec = to.Service.Spec
					if _, err := c.kubeclient.CoreV1().Services(ns).Update(ctx, existing, metav1.UpdateOptions{}); err != nil {
						return err
					}
				}
			} else {
				if err := c.kubeclient.CoreV1().Services(ns).Delete(ctx, from.Service.Name, metav1.DeleteOptions{}); err != nil {
					return err
				}
				if _, err := c.kubeclient.CoreV1().Services(ns).Create(ctx, to.Service, metav1.CreateOptions{}); err != nil {
					return err
				}
			}

			if from.Endpoints != nil && to.Endpoints != nil {
				if !equality.Semantic.DeepEqual(from.Endpoints.Subsets, to.Endpoints.Subsets) {
					// Don't modify the informers copy.
					existing := from.Endpoints.DeepCopy()
					existing.Subsets = to.Endpoints.Subsets
					if _, err := c.kubeclient.CoreV1().Endpoints(ns).Update(ctx, existing, metav1.UpdateOptions{}); err != nil {
						return err
					}
				}
			} else if from.Endpoints == nil && to.Endpoints == nil {
				// noop
			} else if from.Endpoints == nil {
				if _, err := c.kubeclient.CoreV1().Endpoints(ns).Create(ctx, to.Endpoints, metav1.CreateOptions{}); err != nil {
					return err
				}
			} else if to.Endpoints == nil {
				if err := c.kubeclient.CoreV1().Endpoints(ns).Delete(ctx, from.Endpoints.Name, metav1.DeleteOptions{}); err != nil {
					return err
				}
			}

			return nil
		})
	}

	// TODO(mattmoor): This is where we'd look at the state of the Service and
	// reflect any necessary state into the Route.
	return eg.Wait()
}

func deserializeRollout(ctx context.Context, ro string) *traffic.Rollout {
	if ro == "" {
		return nil
	}
	r := &traffic.Rollout{}
	// Failure can happen if users manually tweaked the
	// annotation or there's etcd corruption. Just log, rollouts
	// are not mission critical.
	if err := json.Unmarshal([]byte(ro), r); err != nil {
		logging.FromContext(ctx).Warnw("Error deserializing Rollout: "+ro,
			zap.Error(err))
		return nil
	}
	if !r.Validate() {
		logging.FromContext(ctx).Warnw("Deserializing Rollout is invalid: " + ro)
		return nil
	}
	return r
}

func (c *Reconciler) reconcileRollout(
	ctx context.Context, r *v1.Route, tc *traffic.Config,
	ingress *netv1alpha1.Ingress) *traffic.Rollout {
	cfg := config.FromContext(ctx)

	// Is there rollout duration specified?
	rd := int(r.RolloutDuration().Seconds())
	if rd == 0 {
		// If not, check if there's a cluster-wide default.
		rd = cfg.Network.RolloutDurationSecs
	}
	curRO := tc.BuildRollout()
	// When rollout is disabled just create the baseline annotation.
	if rd <= 0 {
		return curRO
	}
	// Get the current rollout state as described by the traffic.
	nextStepTime := int64(0)
	logger := logging.FromContext(ctx).Desugar().With(
		zap.Int("durationSecs", rd))
	logger.Debug("Rollout is enabled. Stepping from previous state.")
	// Get the previous rollout state from the annotation.
	// If it's corrupt, inexistent, or otherwise incorrect,
	// the prevRO will be just nil rollout.
	prevRO := deserializeRollout(ctx,
		ingress.Annotations[networking.RolloutAnnotationKey])

	// And recompute the rollout state.
	now := c.clock.Now().UnixNano()

	// Now check if the ingress status changed from not ready to ready.
	rtView := r.Status.GetCondition(v1.RouteConditionIngressReady)
	if prevRO != nil && ingress.IsReady() && !rtView.IsTrue() {
		logger.Debug("Observing Ingress not-ready to ready switch condition for rollout")
		prevRO.ObserveReady(ctx, now, float64(rd))
	}

	effectiveRO, nextStepTime := curRO.Step(ctx, prevRO, now)
	if nextStepTime > 0 {
		nextStepTime -= now
		c.enqueueAfter(r, time.Duration(nextStepTime))
		logger.Debug("Re-enqueuing after", zap.Duration("nextStepTime", time.Duration(nextStepTime)))
	}

	// Comparing and diffing isn't cheap so do it only if we're going
	// to actually log the message.
	// Those are well known types, cmp won't panic.
	if logger.Core().Enabled(zapcore.DebugLevel) && !cmp.Equal(prevRO, effectiveRO) {
		logger.Debug("Rollout diff:(-was,+now)",
			zap.String("diff", cmp.Diff(prevRO, effectiveRO)))
	}
	return effectiveRO
}


text:
<?php
namespace Grav\Common;

/**
 * Handles browser and platform versions
 *
 * Internally uses the PhpUserAgent package https://github.com/donatj/PhpUserAgent
 *
 * @author  RocketTHeme
 * @licence MIT
 */
class Browser
{
    protected $useragent = [];

    /**
     * Browser constructor.
     */
    public function __construct()
    {
        try {
            $this->useragent = parse_user_agent();
        } catch (\InvalidArgumentException $e) {
            $this->useragent = parse_user_agent("Mozilla/5.0 (compatible; Unknown;)");
        }
    }

    /**
     * Get the current browser identifier
     *
     * Currently detected browsers:
     *
     * Android Browser
     * BlackBerry Browser
     * Camino
     * Kindle / Silk
     * Firefox / Iceweasel
     * Safari
     * Internet Explorer
     * IEMobile
     * Chrome
     * Opera
     * Midori
     * Vivaldi
     * TizenBrowser
     * Lynx
     * Wget
     * Curl
     *
     * @return string the lowercase browser name
     */
    public function getBrowser()
    {
        return strtolower($this->useragent['browser']);
    }

    /**
     * Get the current platform identifier
     *
     * Currently detected platforms:
     *
     * Desktop
     *   -> Windows
     *   -> Linux
     *   -> Macintosh
     *   -> Chrome OS
     * Mobile
     *   -> Android
     *   -> iPhone
     *   -> iPad / iPod Touch
     *   -> Windows Phone OS
     *   -> Kindle
     *   -> Kindle Fire
     *   -> BlackBerry
     *   -> Playbook
     *   -> Tizen
     * Console
     *   -> Nintendo 3DS
     *   -> New Nintendo 3DS
     *   -> Nintendo Wii
     *   -> Nintendo WiiU
     *   -> PlayStation 3
     *   -> PlayStation 4
     *   -> PlayStation Vita
     *   -> Xbox 360
     *   -> Xbox One
     *
     * @return string the lowercase platform name
     */
    public function getPlatform()
    {
        return strtolower($this->useragent['platform']);
    }

    /**
     * Get the current full version identifier
     *
     * @return string the browser full version identifier
     */
    public function getLongVersion()
    {
        return $this->useragent['version'];
    }

    /**
     * Get the current major version identifier
     *
     * @return string the browser major version identifier
     */
    public function getVersion()
    {
        $version = explode('.', $this->getLongVersion());

        return intval($version[0]);
    }

    /**
     * Determine if the request comes from a human, or from a bot/crawler
     *
     * @return bool
     */
    public function isHuman()
    {
        $browser = $this->getBrowser();
        if (empty($browser)) {
            return false;
        }

        if (preg_match('~(bot|crawl)~i', $browser)) {
            return false;
        }

        return true;
    }
}


text:
package fi.iki.elonen.integration;

import fi.iki.elonen.NanoHTTPD;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.After;
import org.junit.Before;

import java.io.IOException;

/**
 * @author Paul S. Hawke (paul.hawke@gmail.com)
 *         On: 9/2/13 at 10:02 PM
 */
public abstract class IntegrationTestBase<T extends NanoHTTPD> {
    protected DefaultHttpClient httpclient;
    protected T testServer;

    @Before
    public void setUp() {
        testServer = createTestServer();
        httpclient = new DefaultHttpClient();
        try {
            testServer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @After
    public void tearDown() {
        httpclient.getConnectionManager().shutdown();
        testServer.stop();
    }

    public abstract T createTestServer();
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package fertilizers;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author ProjectTeam
 */
public class DateUtil {

    private static final long DAY_IN_MILLISECONDS = 86400000L; //one day in milliseconds

    /**
     * Returns 'date' as it is if number of days to add is 0

     * Forwards date by as many days as given by 'days' if 'days' is
     * positive

     * Advances date by as many days as given by 'days' if 'days' is
     * negative

     *
     * @param date
     * @param days
     * @return
     */
    public static java.util.Date addDaysToDate(java.util.Date date, int days) {

        return new java.util.Date(date.getTime() + (days * DAY_IN_MILLISECONDS));

    }

    /**
     * returns true if "from" date is less than "to" date. In all other cases,
     * returns false
     *
     * @param from
     * @param to
     * @return
     */
    public static boolean compareDate(java.util.Date from, java.util.Date to) {

        return DateUtil.dateDiff(from, to) >= 0;
    }

    /**
     * Returns the difference between two dates in number of milliseconds
     *
     * @param from
     * @param to
     * @return
     */
    public static long dateDiff(java.util.Date from, java.util.Date to) throws NullPointerException{
        return (to.getTime() - from.getTime());
    }

    /**
     * Only if the difference between DAte Of Admission and Date of Birth is
     * more than 18 years and less than 25 years, returns true.
     *
     * In all other cases, returns false
     *
     * @param doa
     * @param dob
     * @return
     */
    public static boolean isAllowedAgeForCollege(java.util.Date doa, java.util.Date dob) {
        double days = 0;
        long years = 0;

        Double daysInMilSec = new Double(DateUtil.DAY_IN_MILLISECONDS);

        days = DateUtil.dateDiff(dob, doa);

        if (days > 0) {
            years = Math.round(days / (365 * daysInMilSec)); //*approximation

            if (years >= 18 && years <= 25) {
                return true;
            }
        }

        return false;
    }

    /**
     * Returns true if and only if "date" is greater than "today"
     *
     * @param date
     * @return
     */
    public static boolean isInFuture(java.util.Date date) {
        java.util.Date today = new java.util.Date();
        return (DateUtil.dateDiff(today, date) > 0);
    }

    /**
     * Returns true if and only if "date" is less than "today"
     *
     * @param date
     * @return
     */
    public static boolean isInPast(java.util.Date date) {
        java.util.Date today = new java.util.Date();
        return (DateUtil.dateDiff(today, date) < 0);
    }

    /**
     * Validate if the given Date string is in the format dd/mm/yyyy and if it
     * can be converted to java.util.Date in dd/mm/yyyy format
     *
     */
    public static boolean validateSimpleDate(String dateText) {

        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
        formatter.setLenient(false);
        Date date;
        try {
            date = formatter.parse(dateText);
        } catch (ParseException pe) {
            return false;
        }

        return true;
    }

    public static java.util.Date strinToDate(String dateText) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        java.util.Date util_date = sdf.parse(dateText);

        return util_date;
    }

    public static String dateToString(java.util.Date date) throws Exception{

//        System.out.println("Expiry Date : " + date);
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        return sdf.format(date);
    }
}


text:
	/* full width css */

	/* this CSS file is no longer needed  - you may delete the file reference from your project*/


text:
module Mac
  module EventMonitor
    class Monitor
      def initialize
        @listeners     = {}
        @any_listeners = []
      end

      def add_listener(type = nil, &block)
        if type
          @listeners[type] ||= []
          @listeners[type] << block
        else
          @any_listeners << block
        end
      end

      def run(stop_after = nil)
        run_app(stop_after)
      end

      def receive_event(str, time, screen_height)
        event = Event.create_from_description(str, time, screen_height)

        (@listeners[event.type] || []).each do |block|
          block.call(event)
        end

        @any_listeners.each do |block|
          block.call(event)
        end
      end
    end
  end
end


text:
<?xml version='1.0' encoding='UTF-8'?>
<resources>
  <string name="donations__button_close">Sulje</string>
  <string name="donations__flattr">Flattr</string>
  <string name="donations__flattr_description">Flattr ottaa 10% kuukausipalkkiosta!</string>
  <string name="donations__google_android_market">Googlen Android Market</string>
  <string name="donations__google_android_market_not_supported">Sovelluksen sisäiset lahjoitukset eivät ole tuettu. Löytyykö laitteesta Android Market?</string>
  <string name="donations__google_android_market_description">Gogle ottaa 30% jokaisesta lahjoituksesta!</string>
  <string name="donations__google_android_market_donate_button">Lahjoita!</string>
  <string name="donations__google_android_market_text">Kuinka paljon?</string>
  <string name="donations__paypal">PayPal</string>
  <string name="donations__paypal_description">Voit valita, kuinka paljon haluat lahjoittaa painikkeen napsauttamisen jälkeen!</string>
  <string name="donations__thanks_dialog_title">Kiitos!</string>
  <string name="donations__thanks_dialog">Kiitos lahjoituksestasi!\nArvostan sitä suuresti!</string>
</resources>


text:
module.exports = function(err, req, res, next) { //eslint-disable-line
    const code = err.code || 500;
    const error = code === 500 ? 'Internal Server Error' : err.error; //if code is 500, then inteneral server err, else err.error
    console.log(err.error || err.message);
    res.status(code).send({error});
};


text:
#include "global.h"
#include "video.h"
#include "taisei_err.h"
#include <stdlib.h>

static VideoMode common_modes[] = {
	{RESX, RESY},

	{640, 480},
	{800, 600},
	{1024, 768},
	{1280, 960},
	{1152, 864},
	{1400, 1050},
	{1440, 1080},

	{0, 0},
};

static void video_add_mode(int width, int height) {
	if(video.modes) {
		int i; for(i = 0; i < video.mcount; ++i) {
			VideoMode *m = &(video.modes[i]);
			if(m->width == width && m->height == height)
				return;
		}
	}

	video.modes = (VideoMode*)realloc(video.modes, (++video.mcount) * sizeof(VideoMode));
	video.modes[video.mcount-1].width  = width;
	video.modes[video.mcount-1].height = height;
}

static int video_compare_modes(const void *a, const void *b) {
	VideoMode *va = (VideoMode*)a;
	VideoMode *vb = (VideoMode*)b;
	return va->width * va->height - vb->width * vb->height;
}

static void _video_setmode(int w, int h, int fs, int fallback) {
	int flags = SDL_OPENGL;
	if(fs) flags |= SDL_FULLSCREEN;

	if(!fallback) {
		video.intended.width = w;
		video.intended.height = h;
	}

	if(display)
		SDL_FreeSurface(display);

	if(!(display = SDL_SetVideoMode(w, h, 32, flags))) {
		if(fallback) {
			errx(-1, "video_setmode(): error opening screen: %s", SDL_GetError());
			return;
		}

		warnx("video_setmode(): setting %dx%d failed, falling back to %dx%d", w, h, RESX, RESY);
		_video_setmode(RESX, RESY, fs, True);
	}

	const SDL_VideoInfo *info = SDL_GetVideoInfo();
	video.current.width = info->current_w;
	video.current.height = info->current_h;

	glViewport(0, 0, video.current.width, video.current.height);
}

void video_setmode(int w, int h, int fs) {
	_video_setmode(w, h, fs, False);
}

int video_isfullscreen(void) {
	return !!(display->flags & SDL_FULLSCREEN);
}

void video_toggle_fullscreen(void) {
	video_setmode(video.intended.width, video.intended.height, !video_isfullscreen());
}

void video_init(void) {
	SDL_Rect **modes;
	int i;

	memset(&video, 0, sizeof(video));

	// First register all resolutions that are available in fullscreen
	modes = SDL_ListModes(NULL, SDL_FULLSCREEN | SDL_HWSURFACE);
	if(!modes) {
		warnx("video_init(): no available fullscreen modes");
		tconfig.intval[FULLSCREEN] = False;
	} else if(modes == (SDL_Rect**)-1) {
		warnx("video_init(): you seem to have a weird video driver");
	} else {
		for(i = 0; modes[i]; ++i) {
			video_add_mode(modes[i]->w, modes[i]->h);
		}
	}

	// Then, add some common 4:3 modes for the windowed mode if they are not there yet.
	// This is required for some multihead setups.
	for(i = 0; common_modes[i].width; ++i)
		video_add_mode(common_modes[i].width, common_modes[i].height);

	// sort it, mainly for the options menu
	qsort(video.modes, video.mcount, sizeof(VideoMode), video_compare_modes);

	video_setmode(tconfig.intval[VID_WIDTH], tconfig.intval[VID_HEIGHT], tconfig.intval[FULLSCREEN]);
	SDL_WM_SetCaption("TaiseiProject", NULL);
}

void video_shutdown(void) {
	SDL_FreeSurface(display);
	free(video.modes);
}


text:
package io.getlime.security.powerauth.lib.dataadapter.model.enumeration;

/**
 * Result of username and password verification.
 *
 *

 *
SUCCEEDED - user ID and password have been verified and verification succeeded.

 *
FAILED - user ID and password have been verified and verification failed.

 *
SKIPPED - verification of user ID and password has not been performed at all.

 *

 *
 * @author Roman Strobl, roman.strobl@wultra.com
 */
public enum UserAuthenticationResult {

    /**
     * Authentication succeeded.
     */
    SUCCEEDED,

    /**
     * Authentication failed.
     */
    FAILED,

    /**
     * Authentication was not performed.
     */
    SKIPPED
}


text:
package com.googlecode.charts4j;

/**
 * Type that describes the labels that appear on the axes. Construct with the
 * {@link AxisLabelsFactory} class.
 *
 *
 * @author Julien Chastang (julien.c.chastang at gmail dot com)
 * @see AxisStyle
 * @see AxisLabelsFactory
 */
public interface AxisLabels extends Kloneable<AxisLabels> {

    /**
     * Set the desired axis style. AxisStyle mutable will be defensively copied
     * upon entry.
     *
     * @param axisStyle
     *            Set the axis style that will define the appearance of the text
     *            along side the axis. Cannot pass in null.
     *
     * @see AxisStyle
     */
    void setAxisStyle(final AxisStyle axisStyle);
}


text:
"""
Violin 7000 Series All-Flash Array ISCSI Volume Driver

Provides ISCSI specific LUN services for V7000 series flash arrays.

This driver requires Concerto v7.5.4 or newer software on the array.

You will need to install the python VMEM REST client:
sudo pip install vmemclient

Set the following in the cinder.conf file to enable the VMEM V7000
ISCSI Driver along with the required flags:

volume_driver=cinder.volume.drivers.violin.v7000_fcp.V7000ISCSIDriver

NOTE: this driver file requires the use of synchronization points for
certain types of backend operations, and as a result may not work
properly in an active-active HA configuration.  See OpenStack Cinder
driver documentation for more information.
"""

import random
import uuid

from cinder.i18n import _, _LE, _LI
from oslo_log import log as logging
from cinder.volume import driver
from cinder.volume.drivers.san import san
from cinder.volume.drivers.violin import v7000_common

LOG = logging.getLogger(__name__)

try:
    from . import version
    __version__ = version.__version__
except Exception:
    # version.py is autogenerated during packaging. If we are running
    # against original source it will not be present.
    __version__ = "unknown"

class V7000ISCSIDriver(driver.ISCSIDriver):
    """Executes commands relating to Violin Memory Arrays."""

    VERSION = '4.0'

    def __init__(self, *args, **kwargs):
        super(V7000ISCSIDriver, self).__init__(*args, **kwargs)
        self.stats = {}
        self.gateway_iscsi_ip_addresses = []
        self.configuration.append_config_values(v7000_common.violin_opts)
        self.configuration.append_config_values(san.san_opts)
        self.common = v7000_common.V7000Common(self.configuration)

        LOG.info(_("Initialized driver %(name)s version: %(vers)s") %
                 {'name': self.__class__.__name__, 'vers': self.VERSION})

    def do_setup(self, context):
        """Any initialization the driver does while starting."""
        super(V7000ISCSIDriver, self).do_setup(context)

        self.common.do_setup(context)

        # Register the client with the storage array
        version = self.VERSION + "-ISCSI"
        self.common.vmem_mg.utility.set_managed_by_openstack_version(
            version, "iSCSI")

        # Getting iscsi IPs from the array is incredibly expensive,
        # so only do it once.
        if self.configuration.iscsi_target_ips == []:
            LOG.warn(_("iSCSI target ip addresses not configured "))
            self.gateway_iscsi_ip_addresses = \
                self.common.vmem_mg.utility.get_iscsi_interfaces()
        else:
            self.gateway_iscsi_ip_addresses = \
                self.configuration.iscsi_target_ips

    def check_for_setup_error(self):
        """Returns an error if prerequisites aren't met."""
        self.common.check_for_setup_error()

        if len(self.gateway_iscsi_ip_addresses) == 0:
            msg = _('No iSCSI IPs configured on SAN gateway')
            raise v7000_common.InvalidBackendConfig(reason=msg)

    def create_volume(self, volume):
        """Creates a volume."""
        self.common._create_lun(volume)

    def create_volume_from_snapshot(self, volume, snapshot):
        """Creates a volume from a snapshot."""
        self.common._create_volume_from_snapshot(snapshot, volume)

    def create_cloned_volume(self, volume, src_vref):
        """Creates a clone of the specified volume."""
        self.common._create_lun_from_lun(src_vref, volume)

    def delete_volume(self, volume):
        """Deletes a volume."""
        self.common._delete_lun(volume)

    def extend_volume(self, volume, new_size):
        """Extend an existing volume's size."""
        self.common._extend_lun(volume, new_size)

    def create_snapshot(self, snapshot):
        """Creates a snapshot."""
        self.common._create_lun_snapshot(snapshot)

    def delete_snapshot(self, snapshot):
        """Deletes a snapshot."""
        self.common._delete_lun_snapshot(snapshot)

    def ensure_export(self, context, volume):
        """Synchronously checks and re-exports volumes at cinder start time."""
        pass

    def create_export(self, context, volume):
        """Exports the volume."""
        pass

    def remove_export(self, context, volume):
        """Removes an export for a logical volume."""
        pass

    def initialize_connection(self, volume, connector):
        """Allow connection to connector and return connection info."""
        resp = {}

        LOG.debug("Initialize_connection: initiator - %(initiator)s  host - "
                  "%(host)s ip - %(ip)s" %
                  {'initiator': connector['initiator'],
                   'host': connector['host'],
                   'ip': connector['ip']})

        iqn = self._get_iqn(connector)

        # pick a random single target to give the connector since
        # there is no multipathing support
        tgt = random.choice(self.gateway_iscsi_ip_addresses)

        resp = self.common.vmem_mg.client.create_client(
            name=connector['host'], proto='iSCSI',
            iscsi_iqns=connector['initiator'])

        # raise if we failed for any reason other than a 'client
        # already exists' error code
        if not resp['success'] and 'Error: 0x900100cd' not in resp['msg']:
            msg = _("Failed to create iscsi client")
            raise v7000_common.ViolinBackendErr(message=msg)

        LOG.debug("Create iscsi tgt- name %(iqn)s: client %(client)s: "
                  "ip %(ip)s " %
                  {'iqn': iqn, 'client': connector['host'],
                   'ip': self.gateway_iscsi_ip_addresses})

        resp = self.common.vmem_mg.client.create_iscsi_target(
            name=iqn, client_name=connector['host'],
            ip=self.gateway_iscsi_ip_addresses, access_mode='ReadWrite')

        # same here, raise for any failure other than a 'target
        # already exists' error code
        if not resp['success'] and 'Error: 0x09024309' not in resp['msg']:
            msg = _("Failed to create iscsi target")
            raise v7000_common.ViolinBackendErr(message=msg)

        lun_id = self._export_lun(volume, iqn, connector)

        properties = {}
        properties['target_discovered'] = False
        properties['target_iqn'] = iqn
        properties['target_portal'] = '%s:%s' % (tgt, '3260')
        properties['target_lun'] = lun_id
        properties['volume_id'] = volume['id']
        properties['access_mode'] = 'rw'

        LOG.debug("Return ISCSI data: %(properties)s.",
                  {'properties': properties})

        return {'driver_volume_type': 'iscsi', 'data': properties}

    def terminate_connection(self, volume, connector, **kwargs):
        """Terminates the connection (target<-->initiator)."""
        iqn = self._get_iqn(connector)
        self._unexport_lun(volume, iqn, connector)

    def get_volume_stats(self, refresh=False):
        """Get volume stats.

        If 'refresh' is True, update the stats first.
        """
        if refresh or not self.stats:
            self._update_volume_stats()
        return self.stats

    def update_migrated_volume(self, ctxt, original_volume, current_volume,
                               original_volume_status=None):
        self.common._update_migrated_volume(original_volume,
			                    current_volume,
					    original_volume_status)

    def _update_volume_stats(self):
        """Gathers array stats and converts them to GB values."""
        data = self.common._get_volume_stats(self.configuration.san_ip)

        backend_name = self.configuration.volume_backend_name
        data['volume_backend_name'] = backend_name or self.__class__.__name__
        data['driver_version'] = __version__
        data['storage_protocol'] = 'iSCSI'
        for i in data:
            LOG.debug("stat update: %(name)s=%(data)s",
                      {'name': i, 'data': data[i]})

        self.stats = data

    def _export_lun(self, volume, target, connector):
        """Generates the export configuration for the given volume.

        :param volume:  volume object provided by the Manager
        :param connector:  connector object provided by the Manager
        :returns: the LUN ID assigned by the backend
        """
        lun_id = ''
        v = self.common.vmem_mg

        LOG.debug("Exporting lun %(vol_id)s - initiator iqns %(i_iqns)s "
                  "- target iqns %(t_iqns)s.",
                  {'vol_id': volume['id'], 'i_iqns': connector['initiator'],
                   't_iqns': self.gateway_iscsi_ip_addresses})

        try:
            lun_id = self.common._send_cmd_and_verify(
                v.lun.assign_lun_to_iscsi_target,
                self._is_lun_id_ready,
                "Assign device successfully",
                [volume['id'], target],
                [volume['id'], connector['host']])

        except v7000_common.ViolinBackendErr:
            LOG.exception(_LE("Backend returned error for lun export."))
            raise

        except Exception:
            raise v7000_common.ViolinInvalidBackendConfig(
                reason=_('LUN export failed!'))

        lun_id = self._get_lun_id(volume['id'], connector['host'])
        LOG.info(_LI("Exported lun %(vol_id)s on lun_id %(lun_id)s."),
                 {'vol_id': volume['id'], 'lun_id': lun_id})

        return lun_id

    def _unexport_lun(self, volume, target, connector):
        """Removes the export configuration for the given volume.

        The equivalent CLI command is "no lun export container
        <container_name> name <lun_name>"

        Arguments:
            volume -- volume object provided by the Manager
        """
        v = self.common.vmem_mg

        LOG.info(_("Unexporting lun %(vol)s host is %(host)s "
                   "target is %(iqn)s") %
                 {'vol': volume['id'], 'host': connector['host'],
                  'iqn': target})

        try:
            self.common._send_cmd(v.lun.unassign_lun_from_iscsi_target,
                                  "Unassign device successfully",
                                  volume['id'], target, True)

        except v7000_common.ViolinBackendErrNotFound:
            LOG.info(_("Lun %s already unexported, continuing"),
                     volume['id'])

        except Exception:
            LOG.exception(_("LUN unexport failed!"))
            raise

    def _is_lun_id_ready(self, volume_name, client_name):
        """Get the lun ID for an exported volume.

        If the lun is successfully assigned (exported) to a client, the
        client info has the lun_id.

        Note: The structure returned for iscsi is different from the
        one returned for FC. Therefore this funtion is here instead of
        common.

        Arguments:
            volume_name -- name of volume to query for lun ID
            client_name -- name of client associated with the volume

        Returns:
            lun_id -- Returns True or False
        """

        lun_id = -1
        lun_id = self._get_lun_id(volume_name, client_name)
        if lun_id != -1:
            return True
        else:
            return False

    def _get_lun_id(self, volume_name, client_name):
        """Get the lun ID for an exported volume.

        If the lun is successfully assigned (exported) to a client, the
        client info has the lun_id.

        Note: The structure returned for iscsi is different from the
        one returned for FC. Therefore this funtion is here instead of
        common.

        Arguments:
            volume_name -- name of volume to query for lun ID
            client_name -- name of client associated with the volume

        Returns:
            lun_id -- integer value of lun ID
        """
        v = self.common.vmem_mg
        lun_id = -1

        client_info = v.client.get_client_info(client_name)

        for x in client_info['ISCSIDevices']:
            if volume_name == x['name']:
                lun_id = x['lun']
                break

        return int(lun_id)

    def _get_iqn(self, connector):
        # The vmemclient connection properties list hostname field may
        # change depending on failover cluster config.  Use a UUID
        # from the backend's IP address to avoid a potential naming
        # issue.
        host_uuid = uuid.uuid3(uuid.NAMESPACE_DNS, self.configuration.san_ip)

        return "%s%s.%s" % (self.configuration.iscsi_target_prefix,
                            connector['host'], host_uuid)


text:
@interface MycollectionViewController : UIViewController

@end


text:
layout: post
title:  "Abi Dalzim's Horrid Wilting"
date:   2015-11-20
source: EE.15
tags: [sorcerer, wizard, level8, necromancy]
---

**8th-level necromancy**

**Casting Time**: 1 action

**Range**: 150 feet

**Components**: V, S, M (a bit of sponge)

**Duration**: Instantaneous

You draw the moisture from every creature in a 30-foot cube centered on a point you choose within range. Each creature in that area must make a Constitution saving throw. Constructs and undead aren't affected, and plants and water elementals make this saving throw with disadvantage. A creature takes 10d8 necrotic damage on a failed save, or half as much damage on a successful one.


text:
package org.codehaus.griffon.maven.plugin;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.codehaus.griffon.maven.tools.GriffonProject;

/**
 * Validate consistency between Griffon and Maven settings.
 *
 * @author Created for Grails by Arnaud HERITIER
 * @author Ported to Griffon by Niels Bech Nielsen
 * @description Validate consistency between Griffon (application.properties) and Maven (pom.xml) settings.
 * @since 1.3
 */
@Mojo(name="validate", defaultPhase=LifecyclePhase.VALIDATE, requiresDependencyResolution=ResolutionScope.RUNTIME)
public class MvnValidateMojo extends AbstractGriffonMojo {

    /**
     * The artifact id of the project.
     *
     */
	@Parameter(defaultValue = "${project.artifactId}", readonly = true)
    private String artifactId;

    /**
     * The version id of the project.
     *
     */
	@Parameter(defaultValue = "${project.version}", readonly = true)
    private String version;

    public void execute() throws MojoExecutionException, MojoFailureException {
        GriffonProject griffonProject;
        try {
            griffonProject = getGriffonServices().readProjectDescriptor();
        } catch (final MojoExecutionException e) {
            getLog().info("No Griffon application found - skipping validation.");
            return;
        }

        if (!artifactId.equals(griffonProject.getAppName())) {
            throw new MojoFailureException("app.name [" + griffonProject.getAppName() + "] in " +
                "application.properties is different of the artifactId [" + artifactId + "] in the pom.xml");
        }

        // We have to set the application version in Griffon settings for old versions
        if (griffonProject.getAppVersion() == null) {
            griffonProject.setAppVersion(GriffonProject.DEFAULT_APP_VERSION);
            getLog().warn("application.properties didn't contain an app.version property");
            getLog().warn("Setting to default value '" + griffonProject.getAppVersion() + "'.");

            getGriffonServices().writeProjectDescriptor(getBasedir(), griffonProject);

        }

        final String pomVersion = version.trim();
        final String griffonVersion = griffonProject.getAppVersion().trim();

        if (!griffonVersion.equals(pomVersion)) {
            throw new MojoFailureException("app.version [" + griffonVersion + "] in " +
                "application.properties is different of the version [" + pomVersion + "] in the pom.xml");
        }

    }
}


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

<meta http-equiv="content-type" content="text/html;charset=utf-8" />

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>ABUELA!! | Eduardo Esclap.es</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <link type="text/css" rel="stylesheet" media="all" href="http://esclap.es/sites/esclap.es/files/css/css_267e79d13662e7dee2ccbe79a7f8f1aa.css" />

      Skip to main content

                                Eduardo Esclap.es

Otro blog, este ya si eso.

Blog

ABUELA!!

Publicado el Vie, 09/12/2005 - 16:38

  Abuela,

Ya me han dicho que sigues mis aventuras en internet... quien iba a decirme que te serías una ciberabuela!!

Y como siempre, escriba lo que escriba, tu no solo estas de acuerdo, sino que además dices "Que bueno es el Edu"

Para reforzarte esa actitud tan positiva, aquí tienes un trocito de mi blog especialmente para ti. Un beso muy grande.

Bueno, tengo otro ciberabuelo en Barcelona y su ciberabuela respectiva que también me siguen (creo) Ya que estoy dedicandome a mi audiencia octogenaria. Besos para ellos también.

Array

        Comentarios

por Alfredo - 09/12/2005 - 18:27

Querido nietoTal como supones, supones bien pues seguimos casi a diario vuestras andanzas por el Extremo Oriente. Creemos que en vuestra próxima etapa de la India encontraréis ocupación a vuestra medida.Sentimos por otro lado mucho de que en las próximas festividades de Navidad no podáis estar con nosotros, sin embargo seréis los principales protagonistas de nuestra conversación y buenos deseos.Un fuerte abrazo de vuestros abuelos cibernéticos de Barcelona

Array

<meta http-equiv="content-type" content="text/html;charset=utf-8" />


text:
var lineCounter = 1;
var funcBlock = {
line1: function (){
	showText("I'm getting up to leave when my new therapist asks me what my \"official\" gender is")
},
line2: function (){
	showText("(for insurance purposes, of course)")
},

line3: function (){
	showText("and I nod and tell him what he already knows.")
},

line4: function (){
	showText("I don't mention how my gender feels more like psychosis than performance,")
},

line5: function (){
	showText("prophetic imaginations of alternate planes.")
},
line6: function (){
	showText("That it makes it easier to breathe when I can tell myself")
},
line7: function (){
	showText("that this body, too, is transient and mutable.")
},

line8: function (){
	showText("I leave that for next session.")
},

line9: function (){
	showText("
\"You're really hard on yourself, huh?\"")
},

line10: function (){
	showText("A question from across a desk above which hang")
},
line11: function (){
	showText("gold lettered degrees and psychoanalytic training certificates.")
},
line12: function (){
	showText("This is the revelation from hours of digging")
},

line13: function (){
	showText("through trauma, medical histories, childhood memories,")
},

line14: function (){
	showText("ruminations, suicidal ideations, accounts of self harm.")
},

line15: function (){
	showText("I should become kinder, it seems.")
},
line16: function (){
	showText("
I am prescribed mindfulness like medication,")
},
line17: function (){
	showText("given my dialectical worksheets and meditation guides.")
},
line18: function (){
	showText("They do not speak of my rainbow body,")
},
line19: function (){
	showText("or of Kannon's infinite compassion,")
},

line20: function (){
	showText("of the diamond or of the womb.")
},

line21: function (){
	showText("If I am diligent in my secular studies, I wonder,")
},
line22: function (){
	showText("will I receive ten thousand hands?")
},
line23: function (){
	showText("
That night I rewrite the poems written for my ex boyfriend,")
},

line24: function (){
	showText("combine them with my medication info sheets,")
},

line25: function (){
	showText("because aestheticizing my pain seems like an artsy thing to do")
},

line26: function (){
	showText("and I've run out of ways to tell him he's hurt me.")
},
line27: function (){
	showText("
I write a new sutra professing my love.")
},
line28: function (){
	showText("I keep the wound agape.")
}
}

Mousetrap.bind("space", function(){
	playLinear();
});

function showText(text) {
	//if($('#bgvid')[0].currentTime > 53){
		$('#textHerePlz').append("
"+text+"
")
		$('#line' + (lineCounter-2).toString()).flyOut(14000);
		lineCounter++;
		$('#bottom')[0].scrollIntoView(false);
	//}
}
function playLinear() {
	if($('#bgvid')[0].currentTime == 0){
		$('#bgvid')[0].play();
		$('#introText').fadeOut(2000)
	} else{
		funcBlock["line"+lineCounter.toString()]()
	}
}
$(document).ready(function(){
    $(document).click(playLinear);
   });

$.fn.flyOut = function(t){
	this.animate({'top':'-300px', 'margin-left': '10%', opacity: 0, 'font-size': '10px'},t, function(){})
}


text:
package org.projectodd.stilts.stomplet;

import org.projectodd.stilts.stomp.StompException;
import org.projectodd.stilts.stomp.StompMessage;
import org.projectodd.stilts.stomp.spi.StompSession;

public interface MessageRouter {

    void send(StompMessage message, StompSession session) throws StompException;

}


text:
<?php

final class PhabricatorUser extends PhabricatorUserDAO implements PhutilPerson {

  const SESSION_TABLE = 'phabricator_session';
  const NAMETOKEN_TABLE = 'user_nametoken';

  protected $phid;
  protected $userName;
  protected $realName;
  protected $sex;
  protected $translation;
  protected $passwordSalt;
  protected $passwordHash;
  protected $profileImagePHID;
  protected $timezoneIdentifier = '';

  protected $consoleEnabled = 0;
  protected $consoleVisible = 0;
  protected $consoleTab = '';

  protected $conduitCertificate;

  protected $isSystemAgent = 0;
  protected $isAdmin = 0;
  protected $isDisabled = 0;

  private $profileImage = null;
  private $profile = null;
  private $status = null;
  private $preferences = null;
  private $omnipotent = false;

  protected function readField($field) {
    switch ($field) {
      case 'timezoneIdentifier':
        // If the user hasn't set one, guess the server's time.
        return nonempty(
          $this->timezoneIdentifier,
          date_default_timezone_get());
      // Make sure these return booleans.
      case 'isAdmin':
        return (bool)$this->isAdmin;
      case 'isDisabled':
        return (bool)$this->isDisabled;
      case 'isSystemAgent':
        return (bool)$this->isSystemAgent;
      default:
        return parent::readField($field);
    }
  }

  public function getConfiguration() {
    return array(
      self::CONFIG_AUX_PHID => true,
      self::CONFIG_PARTIAL_OBJECTS => true,
    ) + parent::getConfiguration();
  }

  public function generatePHID() {
    return PhabricatorPHID::generateNewPHID(
      PhabricatorPHIDConstants::PHID_TYPE_USER);
  }

  public function setPassword(PhutilOpaqueEnvelope $envelope) {
    if (!$this->getPHID()) {
      throw new Exception(
        "You can not set a password for an unsaved user because their PHID ".
        "is a salt component in the password hash.");
    }

    if (!strlen($envelope->openEnvelope())) {
      $this->setPasswordHash('');
    } else {
      $this->setPasswordSalt(md5(mt_rand()));
      $hash = $this->hashPassword($envelope);
      $this->setPasswordHash($hash);
    }
    return $this;
  }

  // To satisfy PhutilPerson.
  public function getSex() {
    return $this->sex;
  }

  public function getTranslation() {
    try {
      if ($this->translation &&
          class_exists($this->translation) &&
          is_subclass_of($this->translation, 'PhabricatorTranslation')) {
        return $this->translation;
      }
    } catch (PhutilMissingSymbolException $ex) {
      return null;
    }
    return null;
  }

  public function isLoggedIn() {
    return !($this->getPHID() === null);
  }

  public function save() {
    if (!$this->getConduitCertificate()) {
      $this->setConduitCertificate($this->generateConduitCertificate());
    }
    $result = parent::save();

    $this->updateNameTokens();

    id(new PhabricatorSearchIndexer())
      ->indexDocumentByPHID($this->getPHID());

    return $result;
  }

  private function generateConduitCertificate() {
    return Filesystem::readRandomCharacters(255);
  }

  public function comparePassword(PhutilOpaqueEnvelope $envelope) {
    if (!strlen($envelope->openEnvelope())) {
      return false;
    }
    if (!strlen($this->getPasswordHash())) {
      return false;
    }
    $password_hash = $this->hashPassword($envelope);
    return ($password_hash === $this->getPasswordHash());
  }

  private function hashPassword(PhutilOpaqueEnvelope $envelope) {
    $hash = $this->getUsername().
            $envelope->openEnvelope().
            $this->getPHID().
            $this->getPasswordSalt();
    for ($ii = 0; $ii < 1000; $ii++) {
      $hash = md5($hash);
    }
    return $hash;
  }

  const CSRF_CYCLE_FREQUENCY  = 3600;
  const CSRF_TOKEN_LENGTH     = 16;

  const EMAIL_CYCLE_FREQUENCY = 86400;
  const EMAIL_TOKEN_LENGTH    = 24;

  public function getCSRFToken($offset = 0) {
    return $this->generateToken(
      time() + (self::CSRF_CYCLE_FREQUENCY * $offset),
      self::CSRF_CYCLE_FREQUENCY,
      PhabricatorEnv::getEnvConfig('phabricator.csrf-key'),
      self::CSRF_TOKEN_LENGTH);
  }

  public function validateCSRFToken($token) {

    if (!$this->getPHID()) {
      return true;
    }

    // When the user posts a form, we check that it contains a valid CSRF token.
    // Tokens cycle each hour (every CSRF_CYLCE_FREQUENCY seconds) and we accept
    // either the current token, the next token (users can submit a "future"
    // token if you have two web frontends that have some clock skew) or any of
    // the last 6 tokens. This means that pages are valid for up to 7 hours.
    // There is also some Javascript which periodically refreshes the CSRF
    // tokens on each page, so theoretically pages should be valid indefinitely.
    // However, this code may fail to run (if the user loses their internet
    // connection, or there's a JS problem, or they don't have JS enabled).
    // Choosing the size of the window in which we accept old CSRF tokens is
    // an issue of balancing concerns between security and usability. We could
    // choose a very narrow (e.g., 1-hour) window to reduce vulnerability to
    // attacks using captured CSRF tokens, but it's also more likely that real
    // users will be affected by this, e.g. if they close their laptop for an
    // hour, open it back up, and try to submit a form before the CSRF refresh
    // can kick in. Since the user experience of submitting a form with expired
    // CSRF is often quite bad (you basically lose data, or it's a big pain to
    // recover at least) and I believe we gain little additional protection
    // by keeping the window very short (the overwhelming value here is in
    // preventing blind attacks, and most attacks which can capture CSRF tokens
    // can also just capture authentication information [sniffing networks]
    // or act as the user [xss]) the 7 hour default seems like a reasonable
    // balance. Other major platforms have much longer CSRF token lifetimes,
    // like Rails (session duration) and Django (forever), which suggests this
    // is a reasonable analysis.
    $csrf_window = 6;

    for ($ii = -$csrf_window; $ii <= 1; $ii++) {
      $valid = $this->getCSRFToken($ii);
      if ($token == $valid) {
        return true;
      }
    }

    return false;
  }

  private function generateToken($epoch, $frequency, $key, $len) {
    $time_block = floor($epoch / $frequency);
    $vec = $this->getPHID().$this->getPasswordHash().$key.$time_block;
    return substr(PhabricatorHash::digest($vec), 0, $len);
  }

  /**
   * Issue a new session key to this user. Phabricator supports different
   * types of sessions (like "web" and "conduit") and each session type may
   * have multiple concurrent sessions (this allows a user to be logged in on
   * multiple browsers at the same time, for instance).
   *
   * Note that this method is transport-agnostic and does not set cookies or
   * issue other types of tokens, it ONLY generates a new session key.
   *
   * You can configure the maximum number of concurrent sessions for various
   * session types in the Phabricator configuration.
   *
   * @param   string  Session type, like "web".
   * @return  string  Newly generated session key.
   */
  public function establishSession($session_type) {
    $conn_w = $this->establishConnection('w');

    if (strpos($session_type, '-') !== false) {
      throw new Exception("Session type must not contain hyphen ('-')!");
    }

    // We allow multiple sessions of the same type, so when a caller requests
    // a new session of type "web", we give them the first available session in
    // "web-1", "web-2", ..., "web-N", up to some configurable limit. If none
    // of these sessions is available, we overwrite the oldest session and
    // reissue a new one in its place.

    $session_limit = 1;
    switch ($session_type) {
      case 'web':
        $session_limit = PhabricatorEnv::getEnvConfig('auth.sessions.web');
        break;
      case 'conduit':
        $session_limit = PhabricatorEnv::getEnvConfig('auth.sessions.conduit');
        break;
      default:
        throw new Exception("Unknown session type '{$session_type}'!");
    }

    $session_limit = (int)$session_limit;
    if ($session_limit <= 0) {
      throw new Exception(
        "Session limit for '{$session_type}' must be at least 1!");
    }

    // NOTE: Session establishment is sensitive to race conditions, as when
    // piping `arc` to `arc`:
    //
    //   arc export ... | arc paste ...
    //
    // To avoid this, we overwrite an old session only if it hasn't been
    // re-established since we read it.

    // Consume entropy to generate a new session key, forestalling the eventual
    // heat death of the universe.
    $session_key = Filesystem::readRandomCharacters(40);

    // Load all the currently active sessions.
    $sessions = queryfx_all(
      $conn_w,
      'SELECT type, sessionKey, sessionStart FROM %T
        WHERE userPHID = %s AND type LIKE %>',
      PhabricatorUser::SESSION_TABLE,
      $this->getPHID(),
      $session_type.'-');
    $sessions = ipull($sessions, null, 'type');
    $sessions = isort($sessions, 'sessionStart');

    $existing_sessions = array_keys($sessions);

    // UNGUARDED WRITES: Logging-in users don't have CSRF stuff yet.
    $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();

    $retries = 0;
    while (true) {

      // Choose which 'type' we'll actually establish, i.e. what number we're
      // going to append to the basic session type. To do this, just check all
      // the numbers sequentially until we find an available session.
      $establish_type = null;
      for ($ii = 1; $ii <= $session_limit; $ii++) {
        $try_type = $session_type.'-'.$ii;
        if (!in_array($try_type, $existing_sessions)) {
          $establish_type = $try_type;
          $expect_key = $session_key;
          $existing_sessions[] = $try_type;

          // Ensure the row exists so we can issue an update below. We don't
          // care if we race here or not.
          queryfx(
            $conn_w,
            'INSERT IGNORE INTO %T (userPHID, type, sessionKey, sessionStart)
              VALUES (%s, %s, %s, 0)',
            self::SESSION_TABLE,
            $this->getPHID(),
            $establish_type,
            $session_key);
          break;
        }
      }

      // If we didn't find an available session, choose the oldest session and
      // overwrite it.
      if (!$establish_type) {
        $oldest = reset($sessions);
        $establish_type = $oldest['type'];
        $expect_key = $oldest['sessionKey'];
      }

      // This is so that we'll only overwrite the session if it hasn't been
      // refreshed since we read it. If it has, the session key will be
      // different and we know we're racing other processes. Whichever one
      // won gets the session, we go back and try again.

      queryfx(
        $conn_w,
        'UPDATE %T SET sessionKey = %s, sessionStart = UNIX_TIMESTAMP()
          WHERE userPHID = %s AND type = %s AND sessionKey = %s',
        self::SESSION_TABLE,
        $session_key,
        $this->getPHID(),
        $establish_type,
        $expect_key);

      if ($conn_w->getAffectedRows()) {
        // The update worked, so the session is valid.
        break;
      } else {
        // We know this just got grabbed, so don't try it again.
        unset($sessions[$establish_type]);
      }

      if (++$retries > $session_limit) {
        throw new Exception("Failed to establish a session!");
      }
    }

    $log = PhabricatorUserLog::newLog(
      $this,
      $this,
      PhabricatorUserLog::ACTION_LOGIN);
    $log->setDetails(
      array(
        'session_type' => $session_type,
        'session_issued' => $establish_type,
      ));
    $log->setSession($session_key);
    $log->save();

    return $session_key;
  }

  public function destroySession($session_key) {
    $conn_w = $this->establishConnection('w');
    queryfx(
      $conn_w,
      'DELETE FROM %T WHERE userPHID = %s AND sessionKey = %s',
      self::SESSION_TABLE,
      $this->getPHID(),
      $session_key);
  }

  private function generateEmailToken(
    PhabricatorUserEmail $email,
    $offset = 0) {

    $key = implode(
      '-',
      array(
        PhabricatorEnv::getEnvConfig('phabricator.csrf-key'),
        $this->getPHID(),
        $email->getVerificationCode(),
      ));

    return $this->generateToken(
      time() + ($offset * self::EMAIL_CYCLE_FREQUENCY),
      self::EMAIL_CYCLE_FREQUENCY,
      $key,
      self::EMAIL_TOKEN_LENGTH);
  }

  public function validateEmailToken(
    PhabricatorUserEmail $email,
    $token) {
    for ($ii = -1; $ii <= 1; $ii++) {
      $valid = $this->generateEmailToken($email, $ii);
      if ($token == $valid) {
        return true;
      }
    }
    return false;
  }

  public function getEmailLoginURI(PhabricatorUserEmail $email = null) {
    if (!$email) {
      $email = $this->loadPrimaryEmail();
      if (!$email) {
        throw new Exception("User has no primary email!");
      }
    }
    $token = $this->generateEmailToken($email);
    $uri = PhabricatorEnv::getProductionURI('/login/etoken/'.$token.'/');
    $uri = new PhutilURI($uri);
    return $uri->alter('email', $email->getAddress());
  }

  public function attachUserProfile(PhabricatorUserProfile $profile) {
    $this->profile = $profile;
    return $this;
  }

  public function loadUserProfile() {
    if ($this->profile) {
      return $this->profile;
    }

    $profile_dao = new PhabricatorUserProfile();
    $this->profile = $profile_dao->loadOneWhere('userPHID = %s',
      $this->getPHID());

    if (!$this->profile) {
      $profile_dao->setUserPHID($this->getPHID());
      $this->profile = $profile_dao;
    }

    return $this->profile;
  }

  public function loadPrimaryEmailAddress() {
    $email = $this->loadPrimaryEmail();
    if (!$email) {
      throw new Exception("User has no primary email address!");
    }
    return $email->getAddress();
  }

  public function loadPrimaryEmail() {
    return $this->loadOneRelative(
      new PhabricatorUserEmail(),
      'userPHID',
      'getPHID',
      '(isPrimary = 1)');
  }

  public function loadPreferences() {
    if ($this->preferences) {
      return $this->preferences;
    }

    $preferences = id(new PhabricatorUserPreferences())->loadOneWhere(
      'userPHID = %s',
      $this->getPHID());

    if (!$preferences) {
      $preferences = new PhabricatorUserPreferences();
      $preferences->setUserPHID($this->getPHID());

      $default_dict = array(
        PhabricatorUserPreferences::PREFERENCE_TITLES => 'glyph',
        PhabricatorUserPreferences::PREFERENCE_EDITOR => '',
        PhabricatorUserPreferences::PREFERENCE_MONOSPACED => '',
        PhabricatorUserPreferences::PREFERENCE_DARK_CONSOLE => 0);

      $preferences->setPreferences($default_dict);
    }

    $this->preferences = $preferences;
    return $preferences;
  }

  public function loadEditorLink($path, $line, $callsign) {
    $editor = $this->loadPreferences()->getPreference(
      PhabricatorUserPreferences::PREFERENCE_EDITOR);

    if (is_array($path)) {
      $multiedit = $this->loadPreferences()->getPreference(
        PhabricatorUserPreferences::PREFERENCE_MULTIEDIT);
      switch ($multiedit) {
        case '':
          $path = implode(' ', $path);
          break;
        case 'disable':
          return null;
      }
    }

    if ($editor) {
      return strtr($editor, array(
        '%%' => '%',
        '%f' => phutil_escape_uri($path),
        '%l' => phutil_escape_uri($line),
        '%r' => phutil_escape_uri($callsign),
      ));
    }
  }

  private static function tokenizeName($name) {
    if (function_exists('mb_strtolower')) {
      $name = mb_strtolower($name, 'UTF-8');
    } else {
      $name = strtolower($name);
    }
    $name = trim($name);
    if (!strlen($name)) {
      return array();
    }
    return preg_split('/\s+/', $name);
  }

  /**
   * Populate the nametoken table, which used to fetch typeahead results. When
   * a user types "linc", we want to match "Abraham Lincoln" from on-demand
   * typeahead sources. To do this, we need a separate table of name fragments.
   */
  public function updateNameTokens() {
    $tokens = array_merge(
      self::tokenizeName($this->getRealName()),
      self::tokenizeName($this->getUserName()));
    $tokens = array_unique($tokens);
    $table  = self::NAMETOKEN_TABLE;
    $conn_w = $this->establishConnection('w');

    $sql = array();
    foreach ($tokens as $token) {
      $sql[] = qsprintf(
        $conn_w,
        '(%d, %s)',
        $this->getID(),
        $token);
    }

    queryfx(
      $conn_w,
      'DELETE FROM %T WHERE userID = %d',
      $table,
      $this->getID());
    if ($sql) {
      queryfx(
        $conn_w,
        'INSERT INTO %T (userID, token) VALUES %Q',
        $table,
        implode(', ', $sql));
    }
  }

  public function sendWelcomeEmail(PhabricatorUser $admin) {
    $admin_username = $admin->getUserName();
    $admin_realname = $admin->getRealName();
    $user_username = $this->getUserName();
    $is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business');

    $base_uri = PhabricatorEnv::getProductionURI('/');

    $uri = $this->getEmailLoginURI();
    $body = <<<EOBODY
Welcome to Phabricator!

{$admin_username} ({$admin_realname}) has created an account for you.

  Username: {$user_username}

To login to Phabricator, follow this link and set a password:

  {$uri}

After you have set a password, you can login in the future by going here:

  {$base_uri}

EOBODY;

    if (!$is_serious) {
      $body .= <<<EOBODY

Love,
Phabricator

EOBODY;
    }

    $mail = id(new PhabricatorMetaMTAMail())
      ->addTos(array($this->getPHID()))
      ->setSubject('[Phabricator] Welcome to Phabricator')
      ->setBody($body)
      ->saveAndSend();
  }

  public function sendUsernameChangeEmail(
    PhabricatorUser $admin,
    $old_username) {

    $admin_username = $admin->getUserName();
    $admin_realname = $admin->getRealName();
    $new_username = $this->getUserName();

    $password_instructions = null;
    if (PhabricatorEnv::getEnvConfig('auth.password-auth-enabled')) {
      $uri = $this->getEmailLoginURI();
      $password_instructions = <<<EOTXT
If you use a password to login, you'll need to reset it before you can login
again. You can reset your password by following this link:

  {$uri}

And, of course, you'll need to use your new username to login from now on. If
you use OAuth to login, nothing should change.

EOTXT;
    }

    $body = <<<EOBODY
{$admin_username} ({$admin_realname}) has changed your Phabricator username.

  Old Username: {$old_username}
  New Username: {$new_username}

{$password_instructions}
EOBODY;

    $mail = id(new PhabricatorMetaMTAMail())
      ->addTos(array($this->getPHID()))
      ->setSubject('[Phabricator] Username Changed')
      ->setBody($body)
      ->saveAndSend();
  }

  public static function describeValidUsername() {
    return 'Usernames must contain only numbers, letters, period, underscore '.
           'and hyphen, and can not end with a period.';
  }

  public static function validateUsername($username) {
    // NOTE: If you update this, make sure to update:
    //
    //  - Remarkup rule for @mentions.
    //  - Routing rule for "/p/username/".
    //  - Unit tests, obviously.
    //  - describeValidUsername() method, above.

    return (bool)preg_match('/^[a-zA-Z0-9._-]*[a-zA-Z0-9_-]$/', $username);
  }

  public static function getDefaultProfileImageURI() {
    return celerity_get_resource_uri('/rsrc/image/avatar.png');
  }

  public function attachProfileImageURI($uri) {
    $this->profileImage = $uri;
    return $this;
  }

  public function loadProfileImageURI() {
    if ($this->profileImage) {
      return $this->profileImage;
    }

    $src_phid = $this->getProfileImagePHID();

    if ($src_phid) {
      $file = id(new PhabricatorFile())->loadOneWhere('phid = %s', $src_phid);
      if ($file) {
        $this->profileImage = $file->getBestURI();
      }
    }

    if (!$this->profileImage) {
      $this->profileImage = self::getDefaultProfileImageURI();
    }

    return $this->profileImage;
  }

  public function getFullName() {
    return $this->getUsername().' ('.$this->getRealName().')';
  }

  public function __toString() {
    return $this->getUsername();
  }

  public static function loadOneWithEmailAddress($address) {
    $email = id(new PhabricatorUserEmail())->loadOneWhere(
      'address = %s',
      $address);
    if (!$email) {
      return null;
    }
    return id(new PhabricatorUser())->loadOneWhere(
      'phid = %s',
      $email->getUserPHID());
  }

/* -(  Omnipotence  )-------------------------------------------------------- */

  /**
   * Returns true if this user is omnipotent. Omnipotent users bypass all policy
   * checks.
   *
   * @return bool True if the user bypasses policy checks.
   */
  public function isOmnipotent() {
    return $this->omnipotent;
  }

  /**
   * Get an omnipotent user object for use in contexts where there is no acting
   * user, notably daemons.
   *
   * @return PhabricatorUser An omnipotent user.
   */
  public static function getOmnipotentUser() {
    static $user = null;
    if (!$user) {
      $user = new PhabricatorUser();
      $user->omnipotent = true;
      $user->makeEphemeral();
    }
    return $user;
  }

}