text:
import { flags } from '@oclif/command';
import Command from '../../command';
import * as cf from '../../utils/common-flags';
import { getBalenaSdk, getVisuals, stripIndent } from '../../utils/lazy';
import type * as BalenaSdk from 'balena-sdk';
import jsyaml = require('js-yaml');
import { tryAsInteger } from '../../utils/validation';

interface FlagsDef {
	help: void;
	composition?: boolean;
}

interface ArgsDef {
	commitOrId: string | number;
}

export default class ReleaseCmd extends Command {
	public static description = stripIndent`
		Get info for a release.
`;
	public static examples = [
		'$ balena release a777f7345fe3d655c1c981aa642e5555',
		'$ balena release 1234567',
	];

	public static usage = 'release <commitOrId>';

	public static flags: flags.Input<FlagsDef> = {
		help: cf.help,
		composition: flags.boolean({
			default: false,
			char: 'c',
			description: 'Return the release composition',
		}),
	};

	public static args = [
		{
			name: 'commitOrId',
			description: 'the commit or ID of the release to get information',
			required: true,
			parse: (commitOrId: string) => tryAsInteger(commitOrId),
		},
	];

	public static authenticated = true;

	public async run() {
		const { args: params, flags: options } = this.parse<FlagsDef, ArgsDef>(
			ReleaseCmd,
		);

		const balena = getBalenaSdk();
		if (options.composition) {
			await this.showComposition(params.commitOrId, balena);
		} else {
			await this.showReleaseInfo(params.commitOrId, balena);
		}
	}

	async showComposition(
		commitOrId: string | number,
		balena: BalenaSdk.BalenaSDK,
	) {
		const release = await balena.models.release.get(commitOrId, {
			$select: 'composition',
		});

		console.log(jsyaml.dump(release.composition));
	}

	async showReleaseInfo(
		commitOrId: string | number,
		balena: BalenaSdk.BalenaSDK,
	) {
		const fields: Array<keyof BalenaSdk.Release> = [
			'id',
			'commit',
			'created_at',
			'status',
			'semver',
			'is_final',
			'build_log',
			'start_timestamp',
			'end_timestamp',
		];

		const release = await balena.models.release.get(commitOrId, {
			$select: fields,
			$expand: {
				release_tag: {
					$select: ['tag_key', 'value'],
				},
			},
		});

		const tagStr = release
			.release_tag!.map((t) => `${t.tag_key}=${t.value}`)
			.join('\n');

		const _ = await import('lodash');
		const values = _.mapValues(
			release,
			(val) => val ?? 'N/a',
		) as Dictionary<string>;
		values['tags'] = tagStr;

		console.log(getVisuals().table.vertical(values, [...fields, 'tags']));
	}
}


text:
"""
basepair.py

Define base pairs in a DNA chain
"""

from collections import OrderedDict
from copy import deepcopy

import numpy as np
import pandas as pd

from fractaldna.dna_models import dnapositions as dpos
from fractaldna.dna_models import molecules
from fractaldna.utils.rotations import eulerMatrix

# Positions in Angstroms
PHOSPHATE_POS = dpos.MoleculeFromAtoms.from_cylindrical(dpos.PHOSPHATE).find_center()
SUGAR_POS = dpos.MoleculeFromAtoms.from_cylindrical(dpos.DEOXYRIBOSE).find_center()
GUANINE_POS = dpos.MoleculeFromAtoms.from_cylindrical(dpos.GUANINE).find_center()
ADENINE_POS = dpos.MoleculeFromAtoms.from_cylindrical(dpos.ADENINE).find_center()
THYMINE_POS = dpos.MoleculeFromAtoms.from_cylindrical(dpos.THYMINE).find_center()
CYTOSINE_POS = dpos.MoleculeFromAtoms.from_cylindrical(dpos.CYTOSINE).find_center()

PHOSPHATE_POS_OPP = dpos.MoleculeFromAtoms.from_cylindrical(
    dpos.PHOSPHATE, inverse=True
).find_center()
SUGAR_POS_OPP = dpos.MoleculeFromAtoms.from_cylindrical(
    dpos.DEOXYRIBOSE, inverse=True
).find_center()
GUANINE_POS_OPP = dpos.MoleculeFromAtoms.from_cylindrical(
    dpos.GUANINE, inverse=True
).find_center()
ADENINE_POS_OPP = dpos.MoleculeFromAtoms.from_cylindrical(
    dpos.ADENINE, inverse=True
).find_center()
THYMINE_POS_OPP = dpos.MoleculeFromAtoms.from_cylindrical(
    dpos.THYMINE, inverse=True
).find_center()
CYTOSINE_POS_OPP = dpos.MoleculeFromAtoms.from_cylindrical(
    dpos.CYTOSINE, inverse=True
).find_center()

class BasePair:
    """
    Defines a base pair

    BasePair(base, chain=-1, position=np.zeros(3), rotation=np.zeros(3))

    Create a base pair defined by a particular base GTAC (in the 5' dirn)

    :param base:   defining base (GATC)
    :param chain:    int to indicate the id of the current DNA macromolecule
    :param position: position of base pair relative to (0, 0, 0)
    :param rotation: rotation euler angles of base pair relative to local xyz
    :param index:    index of base pair in chain
    """

    pairings = {
        "G": [molecules.Guanine, molecules.Cytosine],
        "A": [molecules.Adenine, molecules.Thymine],
        "T": [molecules.Thymine, molecules.Adenine],
        "C": [molecules.Cytosine, molecules.Guanine],
    }
    moleculeNames = [
        "leftPhosphate",
        "leftSugar",
        "leftBasePair",
        "rightPhosphate",
        "rightSugar",
        "rightBasePair",
    ]

    def __init__(
        self,
        base: str,
        chain: int = -1,
        position: np.array = np.zeros(3),
        rotation: np.array = np.zeros(3),
        index: int = 0,
    ):
        """Constructor"""
        if base not in ["G", "A", "T", "C"]:
            raise ValueError("base must be either G, A, T, C")

        # start building at 0, so we can rotate in a neutral frame
        # before translating
        self.position = np.zeros(3)
        self.rmatrix = np.eye(3)
        self.chain = chain
        position = np.array(deepcopy(position), dtype=float)
        rotation = np.array(deepcopy(rotation), dtype=float)

        leftPhosphateRot = np.zeros(3)
        leftPhosphatePos = deepcopy(PHOSPHATE_POS)
        self.leftPhosphate = molecules.Triphosphate(
            strand=0,
            chain=chain,
            position=leftPhosphatePos,
            rotation=leftPhosphateRot,
            index=index,
        )
        leftSugarRot = np.zeros(3)
        leftSugarPos = deepcopy(SUGAR_POS)
        self.leftSugar = molecules.DNASugar(
            strand=0,
            chain=chain,
            position=leftSugarPos,
            rotation=leftSugarRot,
            index=index,
        )

        rightPhosphateRot = np.zeros(3)
        rightPhosphatePos = deepcopy(PHOSPHATE_POS_OPP)
        self.rightPhosphate = molecules.Triphosphate(
            strand=1,
            chain=chain,
            position=rightPhosphatePos,
            rotation=rightPhosphateRot,
            index=index,
        )

        rightSugarRot = np.zeros(3)
        rightSugarPos = deepcopy(SUGAR_POS_OPP)
        self.rightSugar = molecules.DNASugar(
            strand=1,
            chain=chain,
            position=rightSugarPos,
            rotation=rightSugarRot,
            index=index,
        )

        if base == "G":
            leftpos = deepcopy(GUANINE_POS)
            rightpos = deepcopy(CYTOSINE_POS_OPP)
        elif base == "C":
            leftpos = deepcopy(CYTOSINE_POS)
            rightpos = deepcopy(GUANINE_POS_OPP)
        elif base == "T":
            leftpos = deepcopy(ADENINE_POS)
            rightpos = deepcopy(THYMINE_POS_OPP)
        elif base == "A":
            leftpos = deepcopy(THYMINE_POS)
            rightpos = deepcopy(ADENINE_POS_OPP)

        leftBasePairRot = np.zeros(3)
        leftBasePairPos = leftpos

        rightBasePairRot = np.zeros(3)
        rightBasePairPos = rightpos

        bases = self.pairings[base]
        self.leftBasePair = bases[0](
            strand=0,
            chain=chain,
            position=leftBasePairPos,
            rotation=leftBasePairRot,
            index=index,
        )
        self.rightBasePair = bases[1](
            strand=1,
            chain=chain,
            position=rightBasePairPos,
            rotation=rightBasePairRot,
            index=index,
        )
        self.molecules = [
            self.leftPhosphate,
            self.leftSugar,
            self.leftBasePair,
            self.rightPhosphate,
            self.rightSugar,
            self.rightBasePair,
        ]

        self.moleculeDict = OrderedDict(zip(self.moleculeNames, self.molecules))

        self.rotate(rotation, about_origin=False)
        self.translate(position)  # sets self.position

    def translate(self, translation: np.array) -> None:
        """
        BasePair.translate(translation)

        translate the base pair by the specified 3-vector array
        """
        for molecule in self.moleculeDict.values():
            molecule.translate(translation)
        self.position = self.position + np.array(translation)
        return None

    def rotate(self, rotation: np.array, about_origin: bool = False) -> None:
        """
        BasePair.rotation(rotation, about_origin=False)

        Rotate elements in base pair

        If about_origin is True, the rotation is with respect to (0, 0, 0)
        If about_origin is False, the rotation is with respect to the base pair position
        """
        if rotation.size == 3:
            rmatrix = eulerMatrix(rotation[0], rotation[1], rotation[2])
        elif rotation.shape == (3, 3):
            rmatrix = rotation
        else:
            return NotImplementedError("The rotation was invalid")

        self.rmatrix = np.dot(rmatrix, self.rmatrix)
        if about_origin is True:
            self.position = np.dot(rmatrix, self.position)

        for molecule in self.moleculeDict.values():
            if about_origin is True:
                molecule.position = np.dot(rmatrix, molecule.position)
            else:
                local_pos = molecule.position - self.position
                molecule.position = np.dot(rmatrix, local_pos) + self.position
            molecule.rotate(rotation)

        return None

    def getCenter(self) -> np.array:
        """
        basepair.getCenter()

        Get the geometric center of the base-pair
        (non-weighted average molecule position)
        """
        positions = [mol.position for mol in self.moleculeDict.values()]
        return np.mean(np.array(positions), axis=1)

    def setNewChain(self, chainIdx: int) -> None:
        """
        BasePair.setNewChain(chainIdx)

        Reset the chain index for all molecules and the base pair
        """
        self.chain = chainIdx
        for molecule in self.moleculeDict.values():
            molecule.chain = chainIdx

        return None

    def set_bp_index(self, bp_idx: int) -> None:
        """
        BasePair.setNewChain(chainIdx)

        Reset the chain index for all molecules
        """
        for molecule in self.moleculeDict.values():
            molecule.index = bp_idx

        return None

    def to_text(self, seperator: str = " ") -> str:
        """
        BasePair.to_text(self, seperator=" ")
        Return a description of the molecules in the base pair as text
        """
        output = []
        for molecule in self.moleculeDict.values():
            output.append(molecule.to_text(seperator=seperator))

        return "".join(output)

    def to_frame(self) -> pd.DataFrame:
        """Return base pair as data frame of molecules"""
        return pd.DataFrame([mol.to_series() for mol in self.moleculeDict.values()])

    def __getitem__(self, key: str) -> molecules.Molecule:
        return self.moleculeDict[key]

    def iterMolecules(self):
        return self.moleculeDict.items()

redpajama_set_name: RedPajamaGithub


text:
window.Tea = Backbone.Model.extend({
	// Specify a urlRoot when using a model outside
	// of a collection (like when deleteTea), to enable the
	// default url function to generate URLs based
	// on the model id. "[urlRoot]/id"
	urlRoot:"./api/teas",
	defaults: {
		"id"       : null,
		"brand"    : "brand name",
		"name"     : "tea name",
		"serving"  : "serving",
		"servings" : 0,
		"ingredients": "",
		"description": "",
		"picture"  : "blank-photo.jpg"
	}

});

window.TeaCollection = Backbone.Collection.extend({
    model:Tea,
	// Set the url property (or function) on a collection
	// to reference its location on the server.
    url:"./api/teas"
});

// Views
window.TeaListView = Backbone.View.extend({
    tagName:'ul',

    initialize:function () {

		var self = this;
		this.teaListItemViews = {};
		// be triggered when new model created
		//    object.on(event, callback, [context]) Alias: bind
		this.collection.on("add", function(tea) {
			teaListItemView = new TeaListItemView({model:tea});
			$(self.el).append( teaListItemView.render().el );
			self.teaListItemViews[ tea.cid ] = teaListItemView;
		});

		this.collection.on("remove", function(tea, options) {
			// this == collection (has deleted models)
			// self.$('[view-cid="' + model.cid + '"]').remove();
			self.teaListItemViews[ tea.cid ].close();
			delete self.teaListItemViews[ tea.cid ];
		});
    },

	// Override view default render function with your code
	// that renders the view template from model data, and
	// updates this.el with the new HTML.
    render:function (eventName) {
	    // Underscore function: _.each()
        _.each(this.collection.models, function (tea) {
			// All views have a DOM element at all times
			// which can be accessed by 'this.el'
            $(this.el).append(new TeaListItemView({model:tea}).render().el);
        }, this);

		// A good convention is to return this at the end of
		// render to enable chained calls.
        return this;
    }
});

window.TeaListItemView = Backbone.View.extend({

    tagName:"li",
    template:_.template($('#tpl-tea-list-item').html()),

	initialize: function () {
		this.cid = this.model.cid;
		this.model.on("change", this.render, this);
		//this.model.on("destroy", this.close, this);
	},

    render:function (eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
		// To identify the associated view of each model
		// by model's instance reference (cid) rather attributes.
		// $(this.el).attr('view-cid', this.model.cid);
        return this;
    },

	close: function () {
		// Remove all callback functions
		$(this.el).unbind();
		// Remove the view from DOM
		$(this.el).remove();
	}
});

window.TeaView = Backbone.View.extend({

    template:_.template($('#tpl-tea-details').html()),

	initialize: function () {
		this.model.on("destroy", this.close, this);
		//this.model.on("change", this.render, this);
	},

    render:function (eventName) {
        $(this.el).html(this.template(this.model.toJSON()));
		return this;
    },

	// Using delegateEvents provides a number of advantages
	// over manually using jQuery to bind events to child
	// elements during render.
	// The Backbone events hash allows us to attach event
	// listeners to either el-relative custom selectors, or
	// directly to el if no selector is provided. An event takes
	// the form of a key-value pair
	// 'eventName selector': 'callbackFunction' and a number of
	// DOM event-types are supported, including click, submit,
	// mouseover, dblclick and more.
    events:{
        "click .save"  				:	"saveTea", // upload photo first,
													// then save any change
        "click .delete"				:	"deleteTea",
		"change #changephoto"		:	"changePhoto",// listen changephoto event
		"drop #teaphoto"			:	"dropPhoto",  // listen drop events
		"dragover #teaphoto"		: 	function(e) {
			e.preventDefault();
		}
    },

	saveTea: function () {

		this.model.set({
            name:$('#name').val(),
            brand:$('#brand').val(),
            serving:$('#serving').val(),
            servings:$('#servings').val(),
            ingredients:$('#ingredients').val(),
            description:$('#description').val()
        });
		var self = this;
        if (this.pictureFile) {
			//console.log( this.pictureFile.name);
            this.model.set("picture", this.pictureFile.name);

			// append photo into FormData object
			var fileData = new FormData();
			fileData.append('file', this.pictureFile);

			// upload FormData object by XMLHttpRequest
			$.ajax({
				url: 'api/upload.php',
				type: 'POST',
				data: fileData,
				processData: false,
				cache: false,
				contentType: false
			})
			.done(function () {
				console.log(self.pictureFile.name + ' uploaded successfully !' );
			})
			.fail(function () {
				console.log('Error! An error occurred while uploading '
					+ self.pictureFile.name + ' !' );
				return false;
			});
        };

        if (self.model.isNew()) {
			// Equivalent to instantiating a model with a hash of
			// attributes, saving the model to the server, and adding
			// the model to the set after being successfully created.
			// Creating a model will trigger an immediate "add" event
			// on the collection, a "request" event as the new model
			// is sent to the server, as well as a "sync" event, once
			// the server has responded with the successful creation
			// of the model.
            app.teaList.create( self.model, {
					success: function() {
						console.log('Successful create & save model (id: '
							+ self.model.id + ' )');
						app.navigate('wines/'+self.model.id, false);
					}
			});
        } else {
			// Save model to database (or alternative persistence layer),
			// by delegating to Backbone.sync.
            self.model.save();
			console.log('Successful update model (id: ' + self.model.id + ' )');
        }
		return true;

    },

    deleteTea:function () {
		// Destroys the model on the server by delegating
		// an HTTP DELETE request to Backbone.sync.
		var self = this;
        this.model.destroy({
            success: function (model) {
				// delete new created model: id == null
                 console.log('Tea (' + self.model.id + ') deleted successfully');
				// $(this.el).unbind();
				// Remove the view from DOM
				// $(this.el).remove();
                // app.navigate('/', true);
            }
        });
		self.close();
		app.navigate('/', false);
        return false;
    },

	changePhoto:function (event) {
		// Prevents the event from bubbling up the DOM tree.
        event.stopPropagation();
		// To prevent the browser default handling of the data:
		// default is open as link on drop.
        event.preventDefault();

		var newFile = event.target.files[0];
		if( ! newFile.type.match(/image.*/i) ){
			alert('Insert an image!');
		} else {
			this.pictureFile = newFile;
			// Read the image file from the local file system
			// and display it in the img tag.
			var reader = new FileReader();
			reader.onloadend = function () {
				$('#teaphoto').attr('src', reader.result);
			};
			reader.readAsDataURL(this.pictureFile);
		}
		return false;
	},

	dropPhoto: function (event) {
        event.stopPropagation();
        event.preventDefault();

		var e = event.originalEvent;
		// The DataTransfer object holding the data.
        e.dataTransfer.dropEffect = 'copy';
        this.pictureFile = e.dataTransfer.files[0];

        // Read the image file from the local file system
		// and display it in the img tag.
        var reader = new FileReader();
        reader.onloadend = function () {
            $('#teaphoto').attr('src', reader.result);
        };
        reader.readAsDataURL(this.pictureFile);
		return false;
    },

	close: function () {
		// Remove all callback functions
		$(this.el).unbind();
		// Remove the view from DOM
		$(this.el).remove();
	}

});

window.HeaderView = Backbone.View.extend({

    template:_.template($('#tpl-header').html()),

    initialize:function () {
        this.render();
    },

    render:function (eventName) {
        $(this.el).html(this.template());
        return this;
    },

    events: {
    //    "click .new": "newTeaEvent"
    },

    newTeaEvent:function (event) {
        app.navigate('teas/new', true);
		return false;
    }

});

// Router
window.AppRouter = Backbone.Router.extend({

    routes:{
        "":				"list",
		"newtea":		"newTea",
        "teas/:id":		"teaDetails"
    },

	initialize:function () {
        $('#header').html(new HeaderView().render().el);
    },

    list:function () {
        this.teaList = new TeaCollection();

		// When the model data returns from the server, it uses set to
		// (intelligently) merge the fetched models, unless you pass
		// {reset: true}, in which case the collection will be reset.
        this.teaList.fetch();

		// When creating a new View, the options passed,like model,
		// collection, etc. are attached to the view as 'this.options'
		// for future reference
        this.teaListView = new TeaListView({collection:this.teaList});

        $('#nav').html(this.teaListView.render().el);

    },

    teaDetails: function (id) {
        this.tea = this.teaList.get(id);
        this.teaView = new TeaView({model:this.tea});
        $('#content').html(this.teaView.render().el);
		$.mobile.changePage( $('#tea-details') );
    },

	newTea: function (event) {
        //if (app.teaView) app.teaView.close();
        this.teaView = new TeaView( { model: new Tea() } );
        $('#newtea-content').html( this.teaView.render().el );
		$.mobile.changePage( $('#new-tea') );
    }

});

var app = new AppRouter();

// When all of Routers have been created, and all routes are set up
// properly, call Backbone.history.start() to begin monitoring
// hashchange events, dispatching routes.
Backbone.history.start();


text:
//
//  TTAlertView.m
//  接口测试
//
//  Created by yuri on 14-11-20.
//  Copyright (c) 2014年 yuri. All rights reserved.
//

#import "TTAlertView.h"

static CGFloat TTAlertViewHeight = 100;
#define TTButtonViewHeight 40

typedef void(^ButtonClickOption)(TTAlertView *alertView);

@interface TTAlertView ()

/** 遮盖图层*/
@property (nonatomic, weak) UIView *cover;
/** 弹窗视图*/
@property (nonatomic, weak) UIView *alertView;
/** 标题label*/
@property (nonatomic, weak) UILabel *titleLabel;
/** 文字label*/
@property (nonatomic, weak) UILabel *messageLabel;
/** 按钮组视图*/
@property (nonatomic, weak) UIView *buttonView;

@property (nonatomic, strong) NSMutableArray *options;

@end

@implementation TTAlertView

- (NSMutableArray *)options
{
    if (_options == nil) {
        _options = [NSMutableArray array];
    }
    return _options;
}

+ (instancetype)alertViewWithHeight:(CGFloat)height
{
    TTAlertViewHeight = height;
    TTAlertView *alert = [[self alloc] init];

    return alert;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {

        self.frame = [UIScreen mainScreen].bounds;

        // 设置遮盖层
        UIView *cover = [[UIView alloc] init];
        cover.frame = [UIScreen mainScreen].bounds;
        cover.backgroundColor = [UIColor blackColor];
        cover.userInteractionEnabled = NO;
        cover.alpha = 0.4;
        [self addSubview:cover];
        self.cover = cover;

        // 设置警告视图
        NSLog(@"%@", NSStringFromCGRect(self.frame));
        UIView *alertView = [[UIView alloc] init];
        CGFloat alertW = cover.frame.size.width * 0.8;
        alertView.bounds = CGRectMake(0, 0, alertW, TTAlertViewHeight);
        alertView.center = CGPointMake(self.center.x, self.center.y - 50);
        [self addSubview:alertView];
        self.alertView = alertView;

        // 添加标题label
        UILabel *titleLabel = [[UILabel alloc] init];
        [self.alertView addSubview:titleLabel];
        self.titleLabel = titleLabel;

        // 添加消息label
        UILabel *messageLabel = [[UILabel alloc] init];
        messageLabel.font = [UIFont systemFontOfSize:14];
        messageLabel.numberOfLines = 0;
        CGFloat messageW = alertView.bounds.size.width * 0.85;
        CGFloat messageX = (alertView.bounds.size.width - messageW) / 2;
        CGFloat messageY = 10;
        CGFloat messageH = alertView.bounds.size.height - TTButtonViewHeight - 20;
        messageLabel.frame = CGRectMake(messageX, messageY, messageW, messageH);
        [self.alertView addSubview:messageLabel];
        self.messageLabel = messageLabel;

        // 添加消息下的分隔线
        UIView *divide = [[UIView alloc] init];
        divide.backgroundColor = [UIColor whiteColor];
        CGFloat divideW = alertView.bounds.size.width;
        CGFloat divideY = CGRectGetMaxY(messageLabel.frame) + 10;
        divide.frame = CGRectMake(0, divideY, divideW, 1);
        [self.alertView addSubview:divide];

        // 设置按钮组视图
        UIView *buttonView = [[UIView alloc] init];
        buttonView.frame = CGRectMake(0, alertView.bounds.size.height - TTButtonViewHeight, alertView.bounds.size.width, TTButtonViewHeight);
        [self.alertView addSubview:buttonView];
        self.buttonView = buttonView;
    }
    return self;
}

- (void)addButtonWithTitle:(NSString *)title option:(void (^)(TTAlertView *))option
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:title forState:UIControlStateNormal];
    [self.options addObject:option];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.buttonView addSubview:btn];
}

- (void)btnClick:(UIButton *)sender
{
    ButtonClickOption option = self.options[sender.tag];
    if (option) {
        option(self);
    }
}

- (void)didMoveToSuperview
{
    int count = (int)self.buttonView.subviews.count;
    CGFloat btnW = self.alertView.bounds.size.width / count;

    for (int i = 0; i < count; i++) {
        CGFloat btnX = btnW * i;
        UIButton *btn = self.buttonView.subviews[i];
        btn.tag = i;
        btn.frame = CGRectMake(btnX, 0, btnW, TTButtonViewHeight);

        if (i) {    //当不为第一个按钮时
            UIView *divide = [[UIView alloc] init];
            divide.backgroundColor = [UIColor whiteColor];
            divide.frame = CGRectMake(btnX, 0, 1, TTButtonViewHeight);
            [self.buttonView addSubview:divide];
        }
    }
}

#pragma mark - 设置alert的属性
- (void)setAlertBackgroundColor:(UIColor *)alertBackgroundColor
{
    _alertBackgroundColor = alertBackgroundColor;
    self.alertView.backgroundColor = alertBackgroundColor;
}

- (void)setMessageColor:(UIColor *)messageColor
{
    _messageColor = messageColor;
    self.messageLabel.textColor = messageColor;
}

- (void)setMessageBackgroundColor:(UIColor *)messageBackgroundColor
{
    _messageBackgroundColor = messageBackgroundColor;
    self.messageLabel.backgroundColor = messageBackgroundColor;
}

- (void)setMessage:(NSString *)message
{
    _message = message;
    self.messageLabel.text = message;
}

#pragma mark - alertView 操作
- (void)showWithSupview:(UIView *)supview
{
    [supview addSubview:self];
}

- (void)closeAlertView
{
    [self removeFromSuperview];
}

@end


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Xenomai: Examples</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

<link rel="search" href="search_opensearch.php?v=opensearch.xml" type="application/opensearchdescription+xml" title="Xenomai"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

Xenomai
    3.0.4

Examples

Here is a list of all examples:

bufp-label.c

bufp-readwrite.c

can-rtt.c

cross-link.c

iddp-label.c

iddp-sendrecv.c

rtcanconfig.c

rtcanrecv.c

rtcansend.c

xddp-echo.c

xddp-label.c

xddp-stream.c

Generated by

     1.8.13


text:
package me.quadphase.qpdex.pokemon;

//
//
//  Generated by StarUML(tm) Java Add-In
//
//  @ Project : QPdex (C) 2015
//  @ File Name : EggGroup.java
//  @ Date : 21-Jul-15
//  @ Author : Nicole
//
//

/**
 * will be used to determine breeding potential of the Pokemon
 */
public class EggGroup {
    /**
     * Name of the egg group
     * Can be:
     * - monster
     * - water 1
     * - water 2
     * - water 3
     * - human-like
     * - bug
     * - mineral
     * - flying
     * - amorphous
     * - field
     * - fairy
     * - ditto
     * - grass
     * - dragon
     * - undiscovered
     * - gender unknown
     */
    private String name;

    /**
     * Constructor
     */
    public EggGroup(String name) {
        this.name = name;
    }

    /**
     * Getter
     */
    public String getName() {
        return name;
    }

    /**
     * Overide for advanced search to display the id and name of type
     *
     * @return id. TypeName in string format
     */
    @Override
    public String toString(){
        return name;
    }
}


text:
package com.microsoft.azure.utility.compute;

import com.microsoft.azure.management.compute.models.ImageReference;
import com.microsoft.azure.management.compute.models.Plan;
import com.microsoft.azure.management.compute.models.VirtualMachine;
import com.microsoft.azure.management.compute.models.VirtualMachineImage;
import com.microsoft.azure.utility.ComputeHelper;
import com.microsoft.azure.utility.ConsumerWrapper;
import com.microsoft.azure.utility.ResourceContext;
import com.microsoft.windowsazure.exception.ServiceException;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class VMMarketplaceTests extends ComputeTestBase {
    static {
        log = LogFactory.getLog(VMMarketplaceTests.class);
    }

    public static final String VMMPublisherName = "datastax";
    public static final String VMMOfferName = "datastax-enterprise-non-production-use-only";
    public static final String VMMSku = "sandbox_single-node";

    @BeforeClass
    public static void setup() throws Exception {
        ensureClientsInitialized();
    }

    @AfterClass
    public static void cleanup() throws Exception {
        log.info("after class, clean resource group: " + m_rgName);
        cleanupResourceGroup();
    }

    @Before
    public void beforeTest() throws Exception {
        setupTest();
    }

    @After
    public void afterTest() throws Exception {
        resetTest();
    }

    @Test
    public void testVMMarketplace() throws Exception {
        log.info("creating VM, in mock: " + IS_MOCKED);
        ResourceContext context = createTestResourceContext(false);

        final VirtualMachineImage image = ComputeHelper.getMarketplaceVMImage(
                computeManagementClient, context.getLocation(), VMMPublisherName, VMMOfferName, VMMSku);

        try
        {
        VirtualMachine vm = createVM(context, generateName("VM"), new ConsumerWrapper<VirtualMachine>() {
            @Override
            public void accept(VirtualMachine vm) {
                vm.getStorageProfile().setDataDisks(null);

                ImageReference ir = new ImageReference();
                ir.setPublisher(VMMPublisherName);
                ir.setOffer(VMMOfferName);
                ir.setSku(VMMSku);
                ir.setVersion(image.getName());
                vm.getStorageProfile().setImageReference(ir);

                Plan plan = new Plan();
                plan.setName(image.getPurchasePlan().getName());
                plan.setProduct(image.getPurchasePlan().getProduct());
                plan.setPromotionCode(null);
                plan.setPublisher(image.getPurchasePlan().getPublisher());
                vm.setPlan(plan);

            }
        });
        } catch (ServiceException se) {
            log.info("Get ServiceException response.");
            Assert.assertTrue("Catch ResourcePurchaseValidationFailed",
                    se.getMessage().contains("ResourcePurchaseValidationFailed"));
        }

        // TODO find a way to set a valid image with purchase plan
        // validateMarketplaceVMPlanField(vm, image);
    }

    private void validateMarketplaceVMPlanField(VirtualMachine vm, VirtualMachineImage image) {
        Assert.assertNotNull(vm.getPlan());
        Assert.assertEquals(image.getPurchasePlan().getPublisher(), vm.getPlan().getPublisher());
        Assert.assertEquals(image.getPurchasePlan().getProduct(), vm.getPlan().getProduct());
        Assert.assertEquals(image.getPurchasePlan().getName(), vm.getPlan().getName());
    }
}


text:
function addUser({input, state}) {
  state.push('live.connectedUsers', input.name);
}

export default addUser;


text:
<!DOCTYPE html>

	<title>Calendar - Hide Other Month Days</title>
	<meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
	<meta name="description" content="" />
	<meta name="keywords" content="" />
	<meta name="author" content="ComponentOne" />

	<link href="../../themes/rocket/jquery-wijmo.css" rel="stylesheet" type="text/css" />

	<link href="../../themes/wijmo/jquery.wijmo.wijcalendar.css" rel="stylesheet" type="text/css"/>

Hide Other Month Days

				In this sample, the showOtherMonthDays option is set to false so that the calendar days for the next and previous month are not shown on the wijcalendar widget.


text:
package edu.isi.karma.semanticlabeling.dsl;

import java.io.*;

/**
 * This class is responsible for creating an object of the data type of each column.
 * @author rutujarane
 */

public class ColumnType implements Serializable{

    String NUMBER = "number";
    String STRING = "string";
    String DATETIME = "datetime";
    String NULL = "null";

    /*public boolean is_comparable(ColumnType self){
        return (self.toString() == self.NUMBER || self.toString() == self.DATETIME);
    }*/
}


text:
<?xml version="1.0" encoding="utf-8" ?>
<Root xmlns="http://15below.com/Substitutions.xsd">
  <Namespaces />
  <Files>
    <File Filename="TestUpdateFiles\TestConfig1.xml">
      <Changes>
        <Change>
          <XPath>/root/value</XPath>
          <ReplacementContent><{{ taggedReplacementContent }}/></ReplacementContent>
        </Change>
      </Changes>
    </File>
    <File Filename="TestUpdateFiles\TestConfig2.xml">
      <Changes>
        <Change>
          <XPath>/root/value</XPath>
          <ReplacementContent><{{ taggedReplacementContent }}/></ReplacementContent>
        </Change>
      </Changes>
    </File>
  </Files>
</Root>


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>7-Up Bundt Cake</title>
      <categories>
        <cat>Cake</cat></categories>
      <yield>16</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>1 1/2</qty>
          <unit>cups</unit></amt>
        <item>Margarine</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit>cups</unit></amt>
        <item>Flour</item></ing>
      <ing>
        <amt>
          <qty>3</qty>
          <unit>cups</unit></amt>
        <item>Sugar</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Realemon</item></ing>
      <ing>
        <amt>
          <qty>5</qty>
          <unit/></amt>
        <item>Eggs</item></ing>
      <ing>
        <amt>
          <qty>3/4</qty>
          <unit>cups</unit></amt>
        <item>7 up (regular; not diet)</item></ing></ingredients>
    <directions>
      <step>  From: mark@alexr.demon.co.uk (Mark Alexander)

  Date: Fri, 25 Nov 1994 16:40:31 GMT
  [I recieved the following recipe from Kelly McGahey @carleton.ca, however
  there wasn't a proper mail address on it and I thought people might be
  interested so i've posted under my name.] [Mark - Co-Mod]

  Here's one out of the "Carleton Cooks" community cookbook, this recipe
  credited to Patrick O'Reilly.

  Cream sugar and margarine and beat until light and fluffy.  Add eggs one at
  a time, and beat well.  Add flour.  Beat in Realemon and 7 Up.  Pour batter
  into well greased and floured Bundt pan.  Bake at 325F for 1 1/4 hours.

  REC.FOOD.RECIPES ARCHIVES

  /CAKES

  From rec.food.cooking archives.  Downloaded from Glen's MM Recipe Archive,
  http://www.erols.com/hosey.

</step></directions></recipe></recipeml>


text:
<!DOCTYPE html>

  <title>Video: Provide captions with the track element</title>

Video: Provide captions with the track element

  <video src="chrome.webm" controls>
    <track src="chrome-subtitles-en.vtt" label="English captions"
           kind="captions" srclang="en" default />

This browser does not support the video element.

  </video>

      Event type:

      Current source file:

      Video size: ×


text:
package nl.rostykerei.cci.ch01.q05;

/**
 * Implementation of {@link OneWay}.
 *
 * @author Rosty Kerei
 */
public final class OneWayImpl implements OneWay {

    @Override
    public boolean isOneAway(final String str1, final String str2) {
        if (Math.abs(str1.length() - str2.length()) > 1) {
            return false;
        }

        char[] bigger;
        char[] smaller;

        if (str1.length() > str2.length()) {
            bigger = str1.toCharArray();
            smaller = str2.toCharArray();
        } else {
            bigger = str2.toCharArray();
            smaller = str1.toCharArray();
        }

        int iSmaller = 0;
        boolean diffFound = false;

        for (char aBigger : bigger) {
            if (iSmaller >= smaller.length || aBigger != smaller[iSmaller]) {
                if (diffFound) {
                    return false;
                }

                diffFound = true;

                if (bigger.length == smaller.length) {
                    iSmaller++;
                }
            } else {
                iSmaller++;
            }
        }

        return diffFound;
    }

}


text:
package net.hexogendev.hexogen.api.entity;

import java.util.Map;

public interface EntityTracker {

	public void registerEntity(Entity entity);

	public void unregisterEntity(Entity entity);

	public void onUpdate();

	public Map<Integer, EntityTrackerEntry> getMapTrackedEntities();

}


text:
**This project is currently a RELEASE CANDIDATE. Please provide feedback on bugs or improvements before the 1.0 release.**

![##candy-wrapper](https://cdn.rawgit.com/apowers313/candy-wrapper/2e325ece/img/candy-wrapper-full-logo-1116x200.png?raw=true)

[![Build Status](https://travis-ci.org/apowers313/candy-wrapper.svg?branch=master)](https://travis-ci.org/apowers313/candy-wrapper)
[![Coverage Status](https://coveralls.io/repos/github/apowers313/candy-wrapper/badge.svg?branch=master)](https://coveralls.io/github/apowers313/candy-wrapper?branch=master)
[![Stories in Ready](https://badge.waffle.io/apowers313/candy-wrapper.png?label=ready&title=Ready)](https://waffle.io/apowers313/candy-wrapper)

[![Sauce Test Status](https://saucelabs.com/browser-matrix/apowers313.svg)](https://saucelabs.com/beta/builds/011f525b0b50411290a7040eaa686fc2)

[Full API Documentation Available Here!](https://apowers313.github.io/candy-wrapper)

Questions, comments, bugs, suggestions, contributions, etc. are welcomed. Please submit an [issue on GitHub](https://github.com/apowers313/candy-wrapper/issues).

## Overview

This library provides the ability to wrap functions or properties so that you can monitor their behavior without changing it. Wrappers also allow you to decide when and how you want to change the behavior of a function or property. Candy-wrapper is similar to wonderful libraries like [Sinon](http://sinonjs.org/) and [shimmer](https://www.npmjs.com/package/shimmer) and can be used for creating stubs, spys, and mocks for testing and monkey patching in production environments. The motivation behind creating candy-wrapper was that other libraries were too hard to learn, had inconsistent APIs, or generally couldn't do the things I needed to do with a wrapper. Hopefully candy-wrapper does everything anyone could ever hope for from a wrapper, or can be easily expanded to add new functionality.

The primary interfaces are Wrapper, Expect, Trigger, and Action:
* [Wrappers](https://apowers313.github.io/candy-wrapper/Wrapper.html) wrap a function or property, so that when the Wrapper is called, so is the underlying function or property.
* You can use [Expect](https://apowers313.github.io/candy-wrapper/Expect.html) to examine what happened with a Wrapper, such as seeing what args were passed to it or what the return value was.
* [Triggers](https://apowers313.github.io/candy-wrapper/Trigger.html) get called just before or just after a function call, providing the opportunity validate Expects or perform Actions. Actions can do things like change arguments recieved by the wrapped function or change the value returned to the caller.

If you are new to wrappers or candy-wrapper, a good place to start is the [Getting Started Tutorial](https://apowers313.github.io/candy-wrapper/tutorial-getting-started.html).

There is also a higher-level interface for defining stubs and tests based on their behavior.
This interface is especially useful for creating stubs and tests that mirror each other, where the stubs can be used to replace a module during testing and a test can make sure that the module has the same behavior as a stub. The primary interface for this functionality is:
* [Module](https://apowers313.github.io/candy-wrapper/Module.html), which defines a group of method and property interfaces, similar to a module that is imported through `require`. After behaviors are defined for the module, stubs and tests can automatically be generated to stub out the module where it is required or test instances of the module.

For a quick introduction to Modules, Intefaces and Behaviors, see the [Modules and Behaviors Tutorial](https://apowers313.github.io/candy-wrapper/modules-and-behaviors.html)

## Installing and Using

### node.js

Install:

``` bash
$ npm install candy-wrapper
```

Use:

``` js
var Wrapper = require("candy-wrapper").Wrapper;
new Wrapper();
```

### Browser

Install:

``` html
<script src=https://rawgit.com/apowers313/candy-wrapper/master/candy-wrapper.js></script>
```

Use:

``` html
<script>
var Wrapper = CandyWrapper.Wrapper;
</script>
```

## Examples
Here are few example use cases to get you started with candy-wrapper...

### Spys
Let's say that you have already written some code and now you want to test it to make sure it works right. Your very simple function `square()` simply takes a number and squares it and you want to make sure it's working right.

``` js
// our simple square function, squares the number passed in
// throws error if the argument isn't a number
var square = function(num) {
    if (typeof num !== "number") {
        throw new TypeError ("expected argument to be Number");
    }

    return num * num;
};

// wrap square so that we can analyze it later
square = new Wrapper(square);

// let's make some calls to square
square(2);
square(4);
try { // gobble up the exception from no arguments
    square();
} catch(e) {}
square(3);
square(5);

square.historyList.filterFirst().expectReturn(4); // true
square.historyList.filterSecond().expectReturn(16); // true
square.historyList.filterThird().expectException(new TypeError ("expected argument to be Number")); // true
square.historyList.filterFourth().expectReturn(10); // false, actually returned 9
square.historyList.filterFifth().expectReturn(23); // false, actually returned 25

square.expectReportAllFailures();
// ExpectError: 2 expectation(s) failed:
//     expectReturn: expectation failed for: 10
//     expectReturn: expectation failed for: 23
```

### Stubs
Let's say you're working on a big complex system that's eventually going to hook up to a database, but you really don't want to have to write all the database code before you can start working on the more interesting code that would rely on it. If only you could create a fake database object that behaved like the real thing...

``` js
var fakeDb = {};
fakeDb.getUser = new Wrapper(); // create a stub function for getUser...
fakeDb.listUsers = new Wrapper(); // create a stub function for listUsers...

// when `fakeDb.getUser` is called with the argument "apwoers", it returns the object below
fakeDb.getUser.triggerOnArgs("apowers")
    .actionReturn({
        username: "apowers",
        firstName: "Adam",
        lastName: "Powers"
    });

// everytime `fakeDb.listUsers` is called, it returns the same array...
fakeDb.listUsers.triggerAlways()
    .actionReturn([{
        username: "apowers",
        firstName: "Adam",
        lastName: "Powers"
    }, {
        username: "bhope",
        firstName: "Bob",
        lastName: "Hope"
    }]);

var user = fakeDb.getUser("apowers"); // returns a user object...
var userList = fakeDb.listUsers(); // returns an array of users...
```

### Mocks
Now let's say it's been a few months, and your system is almost completely done. You have completed your real database, and you're having some sort of error that you suspect is due to your database timing out. You want to simulate errors with your database, but it's not easy to figure out how to make it time out when you want it to. Instead, you can just wrap your database object in a mock and start injecting errors...

``` js
// this is your big complex interface to a MongoDB database
var mysqlDbInterface = {
    // ...
    getUser: function() {
        // make database call here
    }
    // ...
};

var getUserWrapper = new Wrapper(mysqlDbInterface, "getUser");
getUserWrapper.triggerOnCallNumber(2)
    .actionThrowException(new Error("Connection to mySQL timed out"));

// start server
// the third call to `mysqlDbInterface.getUser()` will throw a timeout Error now..
```

### Monkey Patching
Let's say that you are tired of [Math.random()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random) being a pseudo-random number generator and you want it to use your [Digital Random Number Generator (DRNG)](https://software.intel.com/en-us/articles/intel-digital-random-number-generator-drng-software-implementation-guide) instead. Using candy-wrapper, you can [monkey patch](https://en.wikipedia.org/wiki/Monkey_patch) (that is, replace) `Math.random()` with your DRNG:

``` js
// replace "Math.random" with the new function of our choosing...
new Wrapper(Math, "random", function() {
    return 1.2345; // this is where you would call your DRNG...
});

// let's see what it does...
Math.random() // returns 1.2345

// check to see if Math.random is a Wrapper
Wrapper.isWrapper(Math, "random"); // true

// this is probably a bad idea, let's go back to the original random number generator...
Wrapper.unwrap(Math, "random");
```

### Module Stubs and Tests
Changing gears (so to speak), our next example shows how to define a new module that describes the functionality of a car. The {@link Module} can then create a stub to be used where the module is needed during testing, and tests to ensure that any instance of the module will behave properly when imported into the real system.

``` js
// create a new module that will define a car
var carModule = new Module();

// define a function for the module
carModule.defineMethod("startEngine");
// successfully start the engine
carModule.defineBehavior("startEngineSuccess")
    .startEngine()
    .args("key")
    .returns(true);
// fail to start the engine because no key was provided
carModule.defineBehavior("startEngineNoKey")
    .startEngine()
    .args()
    .throws(new Error("no key provided"));

// define a property for the module
carModule.defineProperty("currentSpeed");
// property returns 10 when going slow
carModule.defineBehavior("currentSpeedSlow")
    .currentSpeed()
    .returns(10);
// property returns 70 when at cruising speed
carModule.defineBehavior("currentSpeedCruise")
    .currentSpeed()
    .returns(70);
// property returns 120 when going fast
carModule.defineBehavior("currentSpeedFast")
    .currentSpeed()
    .returns(120);

// define a more complex behavior based on the behaviors we already defined
carModule.defineBehavior("accelerate")
    .startEngineSuccess()
    .currentSpeedSlow()
    .currentSpeedCruise()
    .currentSpeedFast();

/*****************************************************
 * A stub that replaces the functionality for testing
 /****************************************************/

// normally this is what happens
var carModule = require("carModule");

// create a stub that mocks the `startEngineSuccess` behavior
// maybe replace the normal module with your stub using something like Mockery:
// https://www.npmjs.com/package/mockery
var carModule = carModule.getStub("startEngineSuccess");

/*****************************************************
 * A module that will have it's behavior tested
 /****************************************************/

// define which behaviors should be tested for the module
carModule.defineTest("startEngineSuccess", "start the car's engine");
carModule.defineTest("startEngineNoKey", "fails to start the engine without a key");
carModule.defineTest("accelerate", "start the engine and current speed gets faster");

// your instance of the car module
var myFerrari = {
    startEngine = function(key) {
        if (key !== "key") throw new Error ("no key provided");
        return true;
    },
    currentSpeed: 0
};

// maybe your module would do something like this
module.exports = myFerrari;

// run all the tests against your module using the 'describe' and 'it' functions from Mocha
describe ("my ferrari", function() {
    mod.runAllTests(myFerrari, it);
});
```

## Required: JavaScript ES6
Note that this library currently makes exensive use of the features of [JavaScript ES6](http://www.ecma-international.org/ecma-262/6.0/), notably [Proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy), [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), [rest parameters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters), and the [spread operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator). For information about which platforms currently support ES6, see the [ES6 compatibility table](https://kangax.github.io/compat-table/es6/). It has been tested against Node 6 and is tested against the latest versions of Chrome, Firefox, Edge, and Safari.

Presumably it could be back-ported to ES5.1, perhaps drawing on the work of Sinon. The biggest challenge would be removing the use of Proxies. A [pull request](https://github.com/apowers313/candy-wrapper) would be more than welcome if anyone wants to take that challenge on.


text:
export const START = 'START'
export const STOP = 'STOP'
export const TICK = 'TICK'
export const TOGGLE = 'TOGGLE'
export const RESET = 'RESET'
export const RANDOM = 'RANDOM'


text:
package ca.uhn.fhir.jpa.interceptor;

import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;
import ca.uhn.fhir.jpa.api.dao.DaoRegistry;
import ca.uhn.fhir.jpa.provider.r4.BaseResourceProviderR4Test;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.server.exceptions.ResourceGoneException;
import ca.uhn.fhir.rest.server.exceptions.ResourceVersionConflictException;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.r4.model.CarePlan;
import org.hl7.fhir.r4.model.Condition;
import org.hl7.fhir.r4.model.DiagnosticReport;
import org.hl7.fhir.r4.model.Encounter;
import org.hl7.fhir.r4.model.Observation;
import org.hl7.fhir.r4.model.Organization;
import org.hl7.fhir.r4.model.Patient;
import org.hl7.fhir.r4.model.Reference;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;

public class CascadingDeleteInterceptorTest extends BaseResourceProviderR4Test {

	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(CascadingDeleteInterceptorTest.class);
	private IIdType myDiagnosticReportId;

	@Autowired
	private DaoRegistry myDaoRegistry;
	@Autowired
	private IInterceptorBroadcaster myInterceptorBroadcaster;

	private IIdType myPatientId;
	@Autowired
	private CascadingDeleteInterceptor myDeleteInterceptor;
	private IIdType myObservationId;
	private IIdType myConditionId;
	private IIdType myEncounterId;
	@Autowired
	private OverridePathBasedReferentialIntegrityForDeletesInterceptor myOverridePathBasedReferentialIntegrityForDeletesInterceptor;

	@Override
	@AfterEach
	public void after() throws Exception {
		super.after();
		ourRestServer.getInterceptorService().unregisterInterceptor(myDeleteInterceptor);
	}

	public void createResources() {
		Patient p = new Patient();
		p.setActive(true);
		myPatientId = myClient.create().resource(p).execute().getId().toUnqualifiedVersionless();

		Encounter e = new Encounter();
		e.setSubject(new Reference(myPatientId));
		myEncounterId = myClient.create().resource(e).execute().getId().toUnqualifiedVersionless();

		CarePlan cp = new CarePlan();
		cp.setEncounter(new Reference(myEncounterId));
		myClient.create().resource(cp).execute();

		Observation o = new Observation();
		o.setStatus(Observation.ObservationStatus.FINAL);
		o.setSubject(new Reference(myPatientId));
		o.setEncounter(new Reference(myEncounterId));
		myObservationId = myClient.create().resource(o).execute().getId().toUnqualifiedVersionless();

		DiagnosticReport dr = new DiagnosticReport();
		dr.setStatus(DiagnosticReport.DiagnosticReportStatus.FINAL);
		dr.addResult().setReference(myObservationId.getValue());
		dr.setEncounter(new Reference(myEncounterId));
		myDiagnosticReportId = myClient.create().resource(dr).execute().getId().toUnqualifiedVersionless();

		Condition condition = new Condition();
		condition.setSubject(new Reference(myPatientId));
		condition.setAsserter(new Reference(myPatientId));
		condition.setEncounter(new Reference(myEncounterId));
		myConditionId = myClient.create().resource(condition).execute().getId().toUnqualifiedVersionless();
	}

	@Test
	public void testDeleteWithNoInterceptorAndConstraints() {
		createResources();

		try {
			myClient.delete().resourceById(myPatientId).execute();
			fail();
		} catch (ResourceVersionConflictException e) {
			// good
			ourLog.info(myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(e.getOperationOutcome()));
		}
	}

	@Test
	public void testDeleteWithNoRequestObject() {
		createResources();

		myInterceptorRegistry.registerInterceptor(myDeleteInterceptor);

		try {
			myPatientDao.delete(myPatientId);
			fail();
		} catch (ResourceVersionConflictException e) {
			assertThat(e.getMessage(), containsString("because at least one resource has a reference to this resource"));
		}
	}

	@Test
	public void testDeleteWithInterceptorAndConstraints() {
		createResources();

		ourRestServer.getInterceptorService().registerInterceptor(myDeleteInterceptor);

		try {
			myClient.delete().resourceById(myPatientId).execute();
			fail();
		} catch (ResourceVersionConflictException e) {
			String output = myFhirCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(e.getOperationOutcome());
			ourLog.info(output);
			assertThat(output, containsString("Note that cascading deletes are not active for this request. You can enable cascading deletes"));
		}
	}

	@Test
	public void testDeleteCascading() throws IOException {
		createResources();

		ourRestServer.getInterceptorService().registerInterceptor(myDeleteInterceptor);

		HttpDelete delete = new HttpDelete(ourServerBase + "/" + myPatientId.getValue() + "?" + Constants.PARAMETER_CASCADE_DELETE + "=" + Constants.CASCADE_DELETE + "&_pretty=true");
		delete.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_JSON_NEW);
		try (CloseableHttpResponse response = ourHttpClient.execute(delete)) {
			assertEquals(200, response.getStatusLine().getStatusCode());
			String deleteResponse = IOUtils.toString(response.getEntity().getContent(), Charsets.UTF_8);
			ourLog.info("Response: {}", deleteResponse);
			assertThat(deleteResponse, containsString("Cascaded delete to "));
		}

		try {
			ourLog.info("Reading {}", myPatientId);
			myClient.read().resource(Patient.class).withId(myPatientId).execute();
			fail();
		} catch (ResourceGoneException e) {
			// good
		}
	}

	@Test
	public void testDeleteCascadingWithOverridePathBasedReferentialIntegrityForDeletesInterceptorAlsoRegistered() throws IOException {
		ourRestServer.getInterceptorService().registerInterceptor(myOverridePathBasedReferentialIntegrityForDeletesInterceptor);
		try {

			createResources();

			ourRestServer.getInterceptorService().registerInterceptor(myDeleteInterceptor);

			HttpDelete delete = new HttpDelete(ourServerBase + "/" + myPatientId.getValue() + "?" + Constants.PARAMETER_CASCADE_DELETE + "=" + Constants.CASCADE_DELETE + "&_pretty=true");
			delete.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_JSON_NEW);
			try (CloseableHttpResponse response = ourHttpClient.execute(delete)) {
				assertEquals(200, response.getStatusLine().getStatusCode());
				String deleteResponse = IOUtils.toString(response.getEntity().getContent(), Charsets.UTF_8);
				ourLog.info("Response: {}", deleteResponse);
				assertThat(deleteResponse, containsString("Cascaded delete to "));
			}

			try {
				ourLog.info("Reading {}", myPatientId);
				myClient.read().resource(Patient.class).withId(myPatientId).execute();
				fail();
			} catch (ResourceGoneException e) {
				// good
			}

		} finally {
			ourRestServer.getInterceptorService().unregisterInterceptor(myOverridePathBasedReferentialIntegrityForDeletesInterceptor);
		}
	}

	@Test
	public void testDeleteCascadingWithCircularReference() throws IOException {

		Organization o0 = new Organization();
		o0.setName("O0");
		IIdType o0id = myOrganizationDao.create(o0).getId().toUnqualifiedVersionless();

		Organization o1 = new Organization();
		o1.setName("O1");
		o1.getPartOf().setReference(o0id.getValue());
		IIdType o1id = myOrganizationDao.create(o1).getId().toUnqualifiedVersionless();

		o0.getPartOf().setReference(o1id.getValue());
		myOrganizationDao.update(o0);

		ourRestServer.getInterceptorService().registerInterceptor(myDeleteInterceptor);

		HttpDelete delete = new HttpDelete(ourServerBase + "/Organization/" + o0id.getIdPart() + "?" + Constants.PARAMETER_CASCADE_DELETE + "=" + Constants.CASCADE_DELETE + "&_pretty=true");
		delete.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_JSON_NEW);
		try (CloseableHttpResponse response = ourHttpClient.execute(delete)) {
			assertEquals(200, response.getStatusLine().getStatusCode());
			String deleteResponse = IOUtils.toString(response.getEntity().getContent(), Charsets.UTF_8);
			ourLog.info("Response: {}", deleteResponse);
			assertThat(deleteResponse, containsString("Cascaded delete to "));
		}

		try {
			ourLog.info("Reading {}", o0id);
			myClient.read().resource(Organization.class).withId(o0id).execute();
			fail();
		} catch (ResourceGoneException e) {
			// good
		}
		try {
			ourLog.info("Reading {}", o1id);
			myClient.read().resource(Organization.class).withId(o1id).execute();
			fail();
		} catch (ResourceGoneException e) {
			// good
		}
	}

	@Test
	public void testDeleteCascadingByHeader() throws IOException {
		createResources();

		ourRestServer.getInterceptorService().registerInterceptor(myDeleteInterceptor);

		HttpDelete delete = new HttpDelete(ourServerBase + "/" + myPatientId.getValue() + "?_pretty=true");
		delete.addHeader(Constants.HEADER_CASCADE, Constants.CASCADE_DELETE);
		delete.addHeader(Constants.HEADER_ACCEPT, Constants.CT_FHIR_JSON_NEW);
		try (CloseableHttpResponse response = ourHttpClient.execute(delete)) {
			assertEquals(200, response.getStatusLine().getStatusCode());
			String deleteResponse = IOUtils.toString(response.getEntity().getContent(), Charsets.UTF_8);
			ourLog.info("Response: {}", deleteResponse);
			assertThat(deleteResponse, containsString("Cascaded delete to "));
		}

		try {
			ourLog.info("Reading {}", myPatientId);
			myClient.read().resource(Patient.class).withId(myPatientId).execute();
			fail();
		} catch (ResourceGoneException e) {
			// good
		}
	}

}


text:
__author__ = 'kohlmannj'

import abc
from Ity import BaseClass

class Formatter(BaseClass):
    """
    This is the Ity Formatter base class. It contains an abstract method,
    format(), which accepts several input values, including rules, tags,
    tokens, and even the text_str representing the original text, plus an
    optional output_path, and returns:

    * format_output: Either a Formatter-specific data type, or an absolute file
                     path to the file that the Formatter's format() method has
                     written to disk, if the output_path argument is not None.

    Again, different Formatter subclasses will return different values. This is
    potentially poor design, frankly, which is why using the output_path
    argument is strongly recommended---that way, the caller knows it will be
    receiving a file path str.

    Formatters are kind many-headed monsters, as they have free reign over all
    data produced by Ity Tokenizers and Taggers, plus the original text str.
    The tokens and tags lists returned by Ity classes contain enough
    information to reconstruct, for example, an HTML-tagged version of the
    original text using the original token strs (if the tokens were returned by
    a Tokenizer with self.preserve_original_strs = True). The Formatter could
    produce that output using only text_str and a sparse list of tags (meaning
    that there are NOT necessarily tags for every single token or char in the
    text). That said, things can get complicated, so prepare for some confusion
    if you look at, say, StaticHTMLFormatter's Jinja2 templates.

    The Formatters developed for VEP generally required two other fields, which
    are now rolled into this base class: standalone and paginated:

    * **Standalone templates contain all the resources required to display or
      interact with them.**
        * For a Formatter that outputs HTML, for example,
          ``self.standalone = True`` means that the single HTML file returned
          (or written to disk) by self.format() contains all the resources---
          images, data, JavaScript files, etc.---required by the formatted
          output. Essentially, the formatted output is "self-contained".
        * In the same case as above, ``self.standalone = False`` means that the
          HTML output might *not* contain supplementary resources required to
          display or interact with it---instead, a Flask app might be rendering
          the formatted output into a template which *does* load these
          resources.

    * **Paginated** templates output directories.**
    """
    def __init__(
        self,
        debug=False,
        label=None,
        token_str_index=-1,
        token_whitespace_newline_str_index=0,
        standalone=True,
        paginated=False
    ):
        super(Formatter, self).__init__(
            debug=debug,
            label=label
        )
        self.token_str_index = token_str_index
        self.token_whitespace_newline_str_index = token_whitespace_newline_str_index,
        self.standalone = standalone
        self.paginated = paginated

    @abc.abstractmethod
    def format(
        self,
        output_path=None,
        rules=None,
        tags=None,
        tokens=None,
        text_str=None
    ):
        return


text:
@interface HtmlElement_Dt : UIView
@end

#endif	// #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)


text:
Spotify örneğini düşünelim.

3 tane temel veri tipi vardır: Şarkılar, şarkıcılar, dinleyiciler.

Albüm: şarkıcılarla, şarkıları birleştirir.

Çalma listeleri: şarkılarla dinleyicileri birleştirir.

Ürüne yeni özellikler kattıkça, yeni ilişkiler kurarız.

Bu yüzden iş modelimiz giderek karmaşıklaşır ve büyür. Bu birçok projenin batışının nedenidir. Çünkü ilişkisel veritabanlarında, her eklediğiniz yeni özellikle, mevcut şeylerin arasında saklı (implicit) bir join eklemeniz gerekir.

Bu yüzden, alan modellerini inşa etmenin yolu çizge (graph) olmalı.

Datalog, çizge inşa etmenin bir yoludur. Ne ke kadar karmaşık bir alan olursa olsun, `Entity Attribute Value` yöntemiyle bunu modelleyebilirsiniz. Farklı veri yapılarına gerek yoktur.

Github'ı modelleyelim:

		{:user/name "rich"}
		{:user/name "tonsky"}
		{:user/name "pithyless"}

Bu entityleri EAV olarak modelleyelim:

		| e | a | v |
		| 11 | :user/name | rich |
		| 22 | :user/name | tonsky |
		| 33 | :user/name | pithyless |

Bu tablodaki her bir satıra birer datom denir.

Sorgu oluşturmak için pattern matching yaparız.

		[11 _ _]

Pattern matching bir vektördür. 3 öğeden oluşur. EAV yapısını temsil eder.

11: entity id. `_` ne olduğuyla ilgilenmiyorum.

		[_ _ "pithyless"]
		[_ :user/name _]

Variables: Bunlar soru işaretiyle başlar:

		[?e _ _]
		[_ ?a _]
		...

Şimdi bunları birleştirelim:

		[?e :user/name "pithyless"]
		[11 :user/name ?v]

## Sorgulama

Datalog: deklaratif bir mantıksal programlama dilidir.

		[:find ?name
		 :where
		 [11 :user/name ?name]]

Sıralama önemli değil.

Bilinmeyen her şeyi kendisi bulacaktır.

ex01: Single binding

a01:

		[:find ?name
		 :where
		 [_ :user/name ?name]]

->

		{["rich"] ["tonsky"] ["pithyless"]}

a02: `...` ile vektör döner.

		[:find [?name ...]
		 :where
		 [_ :user/name ?name]]

->

		{"rich" "tonsky" "pithyless"}

a03: `.` ile tek öğe döner.

		[:find ?name .
		 :where
		 [_ :user/name ?name]]

->

		{"rich"}

ex02: Multiple bindings

a01:

		[:find ?id ?name
		 :where
		 [?id :user/name ?name]]

->

		{[11 "rich"] [22 "tonsky"] [33 "pithyless"]}

Alan modeline email adresi ekleyelim:

		{:user/name "rich"
		 :user/email "rich@e.com"}
		{:user/name "tonsky"
		 :user/email nikita@e.com}
		{:user/name "pithyless"}

EAV modeli:

		| e | a | v |
		| 11 | :user/name | rich |
		| 22 | :user/name | tonsky |
		| 33 | :user/name | pithyless |

## Şimdi referanslar ekleyelim veri olarak:

		{:org/name "clojure"}

		{:repo/slug "clojure/clojure"
		 :repo/owner 44}

Fakat bu şekilde referansları eklemek çok zor olur. Daha kolay yolu tuple kullanmaktır:

		{:repo/slug "clojure/clojure"
		 :repo/owner [:org/name "clojure"]}

## Follow references

		[:find ?repo
		 :where
		 [?p :user/name "tonsky"]
		 [?r :repo/owner ?p]
		 [?r :repo/slug ?repo]]

Sorgu kriterlerinin sıralaması önemli değil.

## Polymorphic references:

Örneğin, aradığın ismin username veya orgname olmasını önemsemiyorsun. Bu isme ait tüm repoları bulmak istiyorsun.

		[:find ?repo
		 :where
		 (or [?p :org/name ?name]
		     [?p :user/name ?name])
		 [?r :repo/owner ?p]
		 [?r :repo/slug ?repo]]

`or` bir sugar syntax. Buna rule denir. Şöyle de yazabilirdik:

		[:find ?repo
		 :where
		 [(repo-owner ?p ?name)]
		 [?r :repo/owner ?p]
		 [?r :repo/slug ?repo]]

		[[(repo-owner ?p ?name)
		  [?p :org/name ?name]]
		 [(repo-owner ?p ?name)
		  [?p :user/name ?name]]]

rule kendi kendini çağırabilir özyinelemeli bir şekilde. Dolayısıyla graph reversal problemi için uygun bir dildir.

## Circular References

Forking in github. Fork etmeyi nasıl modelleriz?

fork: kaynak repoya bir ref olmalı.

Özyinelemeli bir referans türü. Kendi kendine ref veriyorsun atributta.

		{:repo/slug "pithyless/datascript"
		 :repo/owner [:org/name "pithyless"]
		 :repo/fork [:repo/slug
		             "tonsky/datascript"]}

Tablo veritabanlarında, bunu yaparsan birçok satırı boş bırakırsın. Fakat bu yapıda herhangi bir null yok. Bu sayede mesela forklanmış olan tüm repoları kolayca bulabilirsin:

		[:find ?repo
		 :where
		 [?r :repo/slug ?repo]
		 [?r :repo/fork _]]

Benzer şekilde forklanmış repoların orjinal repolarını bulabilirsin:

		[:find ?repo
		 :where
		 [?r :repo/slug ?repo]
		 [(missing ?r :repo/fork)]]

List forks: Forklanmış repolar için, hem fork repoyu hem orjinal repoyu bulabiliriz:

		[:find ?orig ?fork
		 :where
		 [?orig-id :repo/slug ?orig]
		 [?fork-id :repo/slug ?fork]
		 [?fork-id :repo/fork ?orig-id]

## Multiple values

Bir atribut için birden çok değer olabilir.

		{:repo/slug "clojure/clojure"
		 :repo/lang ["clojure" "java"]

		->

		| e | a | v |
		| 55 | :repo/slug | clojure/clojure |
		| 55 | :repo/lang | clojure |
		| 55 | :repo/lang | java |

Repoların yazıldığı tüm diller?

		[:find ?lang
		 :where
		 [_ :repo/lang ?lang]]

Hangi repo hangi dilde yazılmış?

		[:find ?repo ?lang
		 :where
		 [?r :repo/slug ?repo]
		 [?r :repo/lang ?lang]]

## Multiple References

Bir kişi birden çok repoyu yıldızlayabilir.

		{:user/name "rich"
		 :user/stars
		 [[:repo/slug "clojure/clojure"]
		  [:repo/slug "tonsky/datascript"]]}

Her bir repoyu kaç kişi yıldızlamış?

		[:find ?repo (count ?p)
		 :where
		 [?r :repo/slug ?repo]
		 [?p :user/stars ?r]]

Bu kaç kişinin yıldızladığı, biriktiren (aggregate eden) bir ifade.

## Predicates

Veritabanı özel yüklemler (predicate) tanımlamaya izin vermeli:

		[:find ?repo
		 :where
		 [[_ :repo/slug ?repo]
		  [(.startsWith ?repo "c")]]

`.startsWith` veritabanının çalıştığı host platformdaki (jvm veya js) herhangi bir predicate fonksiyonu olabilir.

Bu örnek, mantıksal programlamayla imperatif programlama dilinin birleşmesine bir örnek. Veritabanı dilinde ne kadar ustalaşırsanız ustalaşın, illa ki imperatif programlamanın imkanlarına ihtiyaç duyacağınız bir vakit gelecektir.

## Fulltext Search

Lucene arama motorunu kullanabilirsin, bu JVM'de çalıştığından. Bu tür fonksiyonları veritabanının kendisinin desteklemesi gerekmez.

		[:find ?repo ?score
		 :where
		 [(fulltext :repo/slug "clojure")
		  [[?r ?repo _ ?score]]]
		->
		∈{["clojure/clojure" 0.99]}

`?score` lucene arama motorunun döndüğü bir değer. Arama sonucunun rank'i anlamına geliyor.

## Databases as indices

Performans nasıl? Çok iyi, çünkü EAV veri yapısını istediğin gibi sıralayarak, her türlü indeksi inşa edebilirsin ve bu sayede her türlü veritabanını modelleyebilirsin.

Örnek: Key/value Database: Redis Key-value store: `AVE`

		| a | v | e |
		| :repo/slug | clojure/clojure | 55 |
		| :repo/slug | pithyless/datascript | 77 |
		| :repo/slug | tonsky/datascript | 66 |

		[:find ?repo
		 :where
		 [_ :repo/slug ?repo]]

Örnek: Row Database: SQL veritabanı: `EAV`

		[:find ?name
		 :where
		 [11 :user/name ?name]]

Örnek: Column Database: Aggregate etme. SQL'da bu ciddi maliyetlidir. `AEV`

		| a | e | v |
		| :user/stars | 11 | 55 |
		| :user/stars | 22 | 55 |
		| :user/stars | 22 | 66 |

		[:find ?p (count ?p)
		 :where
		 [?p :user/stars _]]
		->
		∈{[11 1]
		  [22 2]}

Örnek: Document Database: `EAV`

İçiçe derinlemesine dolaşma:

		[:find ?repo
		 :where
		 [11 :user/stars ?r]
		 [?r :repo/slug ?repo]]

İlk kriterden bir entity'ye ulaşırsın 11 ile. Sonra oradan da `?r` ile başka entity id'ye ulaşıyorsun.

Örnek: Graph Database: `VAE`

Çizge veritabanlarında değerlerden entitylere doğru geriye doğru da gidebilmelisin. Elinde bir yanıt var, ama sorunun ne olduğunu bilmiyorsun.

		[:find ?e
		 :where
		 [?e :user/stars ?r]
		 [?r :repo/slug "clojure/clojure"]]

		v                  a             e
		clojure/clojure -> :repo/slug -> 55
		v     a              e
		55 -> :user/stars -> 11

## Databases as Indices

		| Structure | Index |
		| key/value | A V E |
		| row       | E A V |
		| column    | A E V |
		| document  | E A V |
		| graph     | V A E |
		| search    | inverted-index |

## Reified Attributes

Veri modelimizde tanımladığımız atributların kendileri de, sistemin içinde tanımlanmış birer varlıktır (entity):

		| 11 | :user/name | rich |
		->
		| 2  | :db/ident | :user/name |
		| 11 | 2 | rich |

Bu çok önemli bir özellik. Bir kere homoiconicity burada da var. Yani sistemin kendi kurallarıyla sistemi tarif edebiliyoruz.

İkinci olarak, atributlar aslında birer varlık olduğundan, bunlara da her türlü atribut tanımlayabilirsin. Örneğin:

		| 2  | :db/ident | :user/name |
		| 2  | :db/valueType | :db.type/string |
		| 2  | :db/doc | "Github username" |

## Transactions

Append-only bir veritabanında veri güncelleme (update) nasıl yaparsın?

EAV aslında alan modelleme için yeterlidir. Ancak bu durumda alan, sabittir.

Fakat veri güncellemekten bahsediyorsak aslında alandan değil, zaman içindeki değişim bilgisinin iletmekten bahsediyoruz. Kritik nokta burası.

EAV statik sistemler için yeterli. Ancak dinamik sistemler için 5 kolon gerekir. 2 ekstra kolon: transaction (tx) ve operation (op).

		| e | a | v | tx | op |
		| 11 | :user/name | rich | 1000 | true |

Veri güncelleme, eski veriyi iptal etme (retract) gerektirir:

		| e | a | v | tx | op |
		| 11 | :user/name | rich | 1000 | true |
		| 11 | :user/name | rich | 3000 | false |
		| 11 | :user/name | nick | 4000 | true |

## Reified Transactions

Transactionlar da aynı atributlar gibi birer varlıktır. Dolayısıyla istediğin atributları ekleyebilirsin transactionlar için.

		| e | a | v | tx |
		| 11 | :user/name | rich | 1000 |
		| 1000 | :db/txInstant | 2018-04-... | 1000 |
		| 1000 | :tx/author | Norbert | 1000 |
		| 1000 | :tx/source | Github import ... | 1000 |

Mesela burada, bu güncellemeyi kimin yaptığını (Norbert), bu güncellemenin kaynağı olan veriyi (github import json) takip ediyoruz.

## Time Traveling

		(as-of db 3000)
		(as-of db #inst "2018-04-17")
		(since db #inst "2018-04-17") ;; evvelini unut
		(history db) ;; audit ver
		(filter db #(not= :user/password (:a %))) ;; erişimim olmayan verileri çıkart
		(with db [{:user/name "awkay"}]) ;; hipotetik veritabanı. mevcut veritabanı + bu olgular.

## Pull API

Çıktı veriyi istediğin veri yapısı şekline getirebilirsin.

		[:find (pull ?e query)
		 :where
		 [?e :repo/slug "clojure/clojure"]]

		[:repo/slug
		 :repo/langs
		 {:repo/owner     ;; join işlemi
		  [:user/name     ;; :user/name or :org/name. hangisi varsa olur.
			 :org/name
			 {:repo/_owner  ;; ters join (reverse graph)
			  [(:repo/langs :limit 1)
				 {:repo/commits
				  [:commit/sha]}]}]}]
		->
		[{:repo/slug
		 :repo/langs
		 ["clojure" "java"]  ;; kardinaliteyi kendi çözer
		 :repo/owner        ;; join işlemi
		 {:org/name "clojure"
		  :repo/_owner
		  [{:repo/langs "clojure"}
		 	  :repo/commits [{:commit/sha "bbb"} {:commit/sha "aaaa"}]]}}]

Reverse graph: `:repo/_owner` => `[:find ?r :where [?r :repo/owner ?p]]`

Yani owner = [:org/name "clojure"] olan tüm repoları bul.

## Event Sourcing

Bunun ana sorunu, schema değiştiğinde veri taşıması (migration) yapmaktır.

EAV der ki, schema migration yapmana gerek yok. Bu temel yapıda verilerini tutarsan migrasyon yapmana gerek yok.

## DataScript

Datomic'in js versiyonu. React state yönetimini burada yapabilirsin.

## Pull API

Frontend ve backend arasında iletişim dili.

Pull API'ye ek olarak EQL var. Bununla veri güncellemeleri de yazılabilir, graphql gibi.


text:
    #import <AFNetworking/AFImageDownloader.h>
#else
    #import "AFImageDownloader.h"
#endif

@interface AFGIfImageDownloader : AFImageDownloader

@end


text:
.redux-container-image_select .redux-table-container {
  display: table;
  table-layout: fixed;
  width: 100%;
}
.redux-container-image_select .redux-image-select input[type='radio'] {
  display: none;
}
.redux-container-image_select .redux-image-select-presets img {
  width: 100%;
}
.redux-container-image_select ul.redux-image-select li {
  margin: 0 10px 3px 10px;
  display: inline-block;
  padding: 10px;
  padding-left: 0;
}
.redux-container-image_select .redux-image-select li:last-child {
  margin-bottom: 0;
}
.redux-container-image_select .redux-image-select-selected {
  background-color: #f9f9f9;
}
.redux-container-image_select .redux-image-select img,
.redux-container-image_select .redux-image-select-selected img,
.redux-container-image_select .redux-image-select .tiles,
.redux-container-image_select .redux-image-select-selected .tiles {
  border-width: 4px;
  border-style: solid;
}
.redux-container-image_select .redux-image-select img,
.redux-container-image_select .redux-image-select .tiles {
  border-color: #d9d9d9;
}
.redux-container-image_select .redux-image-select-selected img,
.redux-container-image_select .redux-image-select-selected .tiles {
  border-color: #7a7a7a;
}
.redux-container-image_select .redux-image-select {
  margin: 0 !important;
}
.redux-container-image_select .redux-image-select .tiles {
  display: block;
  background-color: #FFF;
  background-repeat: repeat;
  width: 40px;
  height: 40px;
}


text:
namespace mojo_base::thread_type_unittest {

TEST(ThreadTypeTest, ThreadType) {
  static constexpr base::ThreadType kTestTypes[] = {
      base::ThreadType::kBackground, base::ThreadType::kDefault,
      base::ThreadType::kCompositing, base::ThreadType::kDisplayCritical,
      base::ThreadType::kRealtimeAudio};

  for (auto thread_type_in : kTestTypes) {
    base::ThreadType thread_type_out;

    mojo_base::mojom::ThreadType serialized_thread_type =
        mojo::EnumTraits<mojo_base::mojom::ThreadType,
                         base::ThreadType>::ToMojom(thread_type_in);
    ASSERT_TRUE(
        (mojo::EnumTraits<mojo_base::mojom::ThreadType,
                          base::ThreadType>::FromMojom(serialized_thread_type,
                                                       &thread_type_out)));
    EXPECT_EQ(thread_type_in, thread_type_out);
  }
}

}  // namespace mojo_base::thread_type_unittest


text:
<?php
/**
 * Customize API: WP_Customize_Custom_CSS_Setting class
 *
 * This handles validation, sanitization and saving of the value.
 *
 * @package WordPress
 * @subpackage Customize
 * @since 4.7.0
 */

/**
 * Custom Setting to handle WP Custom CSS.
 *
 * @since 4.7.0
 *
 * @see WP_Customize_Setting
 */
final class WP_Customize_Custom_CSS_Setting extends WP_Customize_Setting {

	/**
	 * The setting type.
	 *
	 * @since 4.7.0
	 * @access public
	 * @var string
	 */
	public $type = 'custom_css';

	/**
	 * Setting Transport
	 *
	 * @since 4.7.0
	 * @access public
	 * @var string
	 */
	public $transport = 'postMessage';

	/**
	 * Capability required to edit this setting.
	 *
	 * @since 4.7.0
	 * @access public
	 * @var string
	 */
	public $capability = 'edit_css';

	/**
	 * Stylesheet
	 *
	 * @since 4.7.0
	 * @access public
	 * @var string
	 */
	public $stylesheet = '';

	/**
	 * WP_Customize_Custom_CSS_Setting constructor.
	 *
	 * @since 4.7.0
	 * @access public
	 *
	 * @throws Exception If the setting ID does not match the pattern `custom_css[$stylesheet]`.
	 *
	 * @param WP_Customize_Manager $manager The Customize Manager class.
	 * @param string               $id      An specific ID of the setting. Can be a
	 *                                      theme mod or option name.
	 * @param array                $args    Setting arguments.
	 */
	public function __construct( $manager, $id, $args = array() ) {
		parent::__construct( $manager, $id, $args );
		if ( 'custom_css' !== $this->id_data['base'] ) {
			throw new Exception( 'Expected custom_css id_base.' );
		}
		if ( 1 !== count( $this->id_data['keys'] ) || empty( $this->id_data['keys'][0] ) ) {
			throw new Exception( 'Expected single stylesheet key.' );
		}
		$this->stylesheet = $this->id_data['keys'][0];
	}

	/**
	 * Add filter to preview post value.
	 *
	 * @since 4.7.9
	 * @access public
	 *
	 * @return bool False when preview short-circuits due no change needing to be previewed.
	 */
	public function preview() {
		if ( $this->is_previewed ) {
			return false;
		}
		$this->is_previewed = true;
		add_filter( 'wp_get_custom_css', array( $this, 'filter_previewed_wp_get_custom_css' ), 9, 2 );
		return true;
	}

	/**
	 * Filter `wp_get_custom_css` for applying the customized value.
	 *
	 * This is used in the preview when `wp_get_custom_css()` is called for rendering the styles.
	 *
	 * @since 4.7.0
	 * @access private
	 * @see wp_get_custom_css()
	 *
	 * @param string $css        Original CSS.
	 * @param string $stylesheet Current stylesheet.
	 * @return string CSS.
	 */
	public function filter_previewed_wp_get_custom_css( $css, $stylesheet ) {
		if ( $stylesheet === $this->stylesheet ) {
			$customized_value = $this->post_value( null );
			if ( ! is_null( $customized_value ) ) {
				$css = $customized_value;
			}
		}
		return $css;
	}

	/**
	 * Fetch the value of the setting. Will return the previewed value when `preview()` is called.
	 *
	 * @since 4.7.0
	 * @access public
	 * @see WP_Customize_Setting::value()
	 *
	 * @return string
	 */
	public function value() {
		if ( $this->is_previewed ) {
			$post_value = $this->post_value( null );
			if ( null !== $post_value ) {
				return $post_value;
			}
		}
		$id_base = $this->id_data['base'];
		$value = '';
		$post = wp_get_custom_css_post( $this->stylesheet );
		if ( $post ) {
			$value = $post->post_content;
		}
		if ( empty( $value ) ) {
			$value = $this->default;
		}

		/** This filter is documented in wp-includes/class-wp-customize-setting.php */
		$value = apply_filters( "customize_value_{$id_base}", $value, $this );

		return $value;
	}

	/**
	 * Validate CSS.
	 *
	 * Checks for imbalanced braces, brackets, and comments.
	 * Notifications are rendered when the customizer state is saved.
	 *
	 * @todo There are cases where valid CSS can be incorrectly marked as invalid when strings or comments include balancing characters. To fix, CSS tokenization needs to be used.
	 *
	 * @since 4.7.0
	 * @access public
	 *
	 * @param string $css The input string.
	 * @return true|WP_Error True if the input was validated, otherwise WP_Error.
	 */
	public function validate( $css ) {
		$validity = new WP_Error();

		if ( preg_match( '#</?\w+#', $css ) ) {
			$validity->add( 'illegal_markup', __( 'Markup is not allowed in CSS.' ) );
		}

		$imbalanced = false;

		// Make sure that there is a closing brace for each opening brace.
		if ( ! $this->validate_balanced_characters( '{', '}', $css ) ) {
			$validity->add( 'imbalanced_curly_brackets', __( 'Your curly brackets {} are imbalanced. Make sure there is a closing } for every opening {.' ) );
			$imbalanced = true;
		}

		// Ensure brackets are balanced.
		if ( ! $this->validate_balanced_characters( '[', ']', $css ) ) {
			$validity->add( 'imbalanced_braces', __( 'Your brackets [] are imbalanced. Make sure there is a closing ] for every opening [.' ) );
			$imbalanced = true;
		}

		// Ensure parentheses are balanced.
		if ( ! $this->validate_balanced_characters( '(', ')', $css ) ) {
			$validity->add( 'imbalanced_parentheses', __( 'Your parentheses () are imbalanced. Make sure there is a closing ) for every opening (.' ) );
			$imbalanced = true;
		}

		// Ensure double quotes are equal.
		if ( ! $this->validate_equal_characters( '"', $css ) ) {
			$validity->add( 'unequal_double_quotes', __( 'Your double quotes " are uneven. Make sure there is a closing " for every opening ".' ) );
			$imbalanced = true;
		}

		/*
		 * Make sure any code comments are closed properly.
		 *
		 * The first check could miss stray an unpaired comment closing figure, so if
		 * The number appears to be balanced, then check for equal numbers
		 * of opening/closing comment figures.
		 *
		 * Although it may initially appear redundant, we use the first method
		 * to give more specific feedback to the user.
		 */
		$unclosed_comment_count = $this->validate_count_unclosed_comments( $css );
		if ( 0 < $unclosed_comment_count ) {
			$validity->add( 'unclosed_comment', sprintf( _n( 'There is %s unclosed code comment. Close each comment with */.', 'There are %s unclosed code comments. Close each comment with */.', $unclosed_comment_count ), $unclosed_comment_count ) );
			$imbalanced = true;
		} elseif ( ! $this->validate_balanced_characters( '/*', '*/', $css ) ) {
			$validity->add( 'imbalanced_comments', __( 'There is an extra */, indicating an end to a comment.  Be sure that there is an opening /* for every closing */.' ) );
			$imbalanced = true;
		}
		if ( $imbalanced && $this->is_possible_content_error( $css ) ) {
			$validity->add( 'possible_false_positive', __( 'Imbalanced/unclosed character errors can be caused by content: ""; declarations. You may need to remove this or add it to a custom CSS file.' ) );
		}

		if ( empty( $validity->errors ) ) {
			$validity = parent::validate( $css );
		}
		return $validity;
	}

	/**
	 * Store the CSS setting value in the custom_css custom post type for the stylesheet.
	 *
	 * @since 4.7.0
	 * @access public
	 *
	 * @param string $css The input value.
	 * @return int|false The post ID or false if the value could not be saved.
	 */
	public function update( $css ) {
		if ( empty( $css ) ) {
			$css = '';
		}

		$r = wp_update_custom_css_post( $css, array(
			'stylesheet' => $this->stylesheet,
		) );

		if ( $r instanceof WP_Error ) {
			return false;
		}
		$post_id = $r->ID;

		// Cache post ID in theme mod for performance to avoid additional DB query.
		if ( $this->manager->get_stylesheet() === $this->stylesheet ) {
			set_theme_mod( 'custom_css_post_id', $post_id );
		}

		return $post_id;
	}

	/**
	 * Ensure there are a balanced number of paired characters.
	 *
	 * This is used to check that the number of opening and closing
	 * characters is equal.
	 *
	 * For instance, there should be an equal number of braces ("{", "}")
	 * in the CSS.
	 *
	 * @since 4.7.0
	 * @access private
	 *
	 * @param string $opening_char The opening character.
	 * @param string $closing_char The closing character.
	 * @param string $css The CSS input string.
	 *
	 * @return bool
	 */
	private function validate_balanced_characters( $opening_char, $closing_char, $css ) {
		return substr_count( $css, $opening_char ) === substr_count( $css, $closing_char );
	}

	/**
	 * Ensure there are an even number of paired characters.
	 *
	 * This is used to check that the number of a specific
	 * character is even.
	 *
	 * For instance, there should be an even number of double quotes
	 * in the CSS.
	 *
	 * @since 4.7.0
	 * @access private
	 *
	 * @param string $char A character.
	 * @param string $css The CSS input string.
	 * @return bool Equality.
	 */
	private function validate_equal_characters( $char, $css ) {
		$char_count = substr_count( $css, $char );
		return ( 0 === $char_count % 2 );
	}

	/**
	 * Count unclosed CSS Comments.
	 *
	 * Used during validation.
	 *
	 * @see self::validate()
	 *
	 * @since 4.7.0
	 * @access private
	 *
	 * @param string $css The CSS input string.
	 * @return int Count.
	 */
	private function validate_count_unclosed_comments( $css ) {
		$count = 0;
		$comments = explode( '/*', $css );

		if ( ! is_array( $comments ) || ( 1 >= count( $comments ) ) ) {
			return $count;
		}

		unset( $comments[0] ); // The first item is before the first comment.
		foreach ( $comments as $comment ) {
			if ( false === strpos( $comment, '*/' ) ) {
				$count++;
			}
		}
		return $count;
	}

	/**
	 * Find "content:" within a string.
	 *
	 * Imbalanced/Unclosed validation errors may be caused
	 * when a character is used in a "content:" declaration.
	 *
	 * This function is used to detect if this is a possible
	 * cause of the validation error, so that if it is,
	 * a notification may be added to the Validation Errors.
	 *
	 * Example:
	 * .element::before {
	 *   content: "(\"";
	 * }
	 * .element::after {
	 *   content: "\")";
	 * }
	 *
	 * Using ! empty() because strpos() may return non-boolean values
	 * that evaluate to false. This would be problematic when
	 * using a strict "false === strpos()" comparison.
	 *
	 * @since 4.7.0
	 * @access private
	 *
	 * @param string $css The CSS input string.
	 * @return bool
	 */
	private function is_possible_content_error( $css ) {
		$found = preg_match( '/\bcontent\s*:/', $css );
		if ( ! empty( $found ) ) {
			return true;
		}
		return false;
	}
}


text:
<footer class="footer-main">
    kt © {{ site.time | date: '%Y' }}
</footer>


text:
package org.antkar.syn.internal.lrtables;

import java.io.PrintStream;
import java.util.List;
import java.util.Map;

import org.antkar.syn.TokenDescriptor;
import org.antkar.syn.internal.Checks;
import org.antkar.syn.internal.CommonUtil;
import org.antkar.syn.internal.parser.ParserEngine;

/**
 * Parser configuration. Defines LR tables and other information used by {@link ParserEngine} to
 * parse a text.
 */
public final class ParserConfiguration {
    private final Map<String, ParserState> startStates;
    private final List<ParserState> states;
    private final List<TokenDescriptor> tokenDescriptors;

    ParserConfiguration(
            Map<String, ParserState> startStates,
            List<ParserState> states,
            List<TokenDescriptor> tokenDescriptors)
    {
        Checks.notNull(startStates);
        Checks.notNull(states);
        Checks.notNull(tokenDescriptors);

        this.startStates = CommonUtil.unmodifiableMapCopy(startStates);
        this.states = CommonUtil.unmodifiableListCopy(states);
        this.tokenDescriptors = CommonUtil.unmodifiableListCopy(tokenDescriptors);
    }

    /**
     * Returns the start LR state for a given start nonterminal.
     */
    public ParserState getStartState(String name) {
        ParserState result = startStates.get(name);
        return result;
    }

    /**
     * Returns the list of token descriptors used in the grammar.
     */
    public List<TokenDescriptor> getTokenDescriptors() {
        return tokenDescriptors;
    }

    /**
     * Prints LR states to a stream. For debug purposes.
     */
    void print(PrintStream out) {
        for (ParserState state : states) {
            state.print(out);
        }
    }
}


text:
### Partnering Organizations:

- Mozilla Gigabit Community Fund
- Austin Monitor (Capital of Texas Media Foundation)
- Nucleus Learning Network
- Civic Party Software
- Open Austin

**Project Purpose:** To promote an awareness of internet health by fostering learners' web literacy, this grant is supporting the development of three interactive web literacy lessons and web apps to facilitate learning.

**What are we working on?**

- Feb 24-26, 2017: Misinfo Con
  - [Saturday Discussion Notes](https://docs.google.com/document/d/1Jkpe0KwSjBbMhZxYXtPIratLiPFKbnGes1G8dzM2Mzo/edit?usp=sharing)
  - Sunday Wireframes for Legit-o-Meter
    - [Mockingbird Link](https://gomockingbird.com/projects/1ai9dty/EbZl46)
    - [Notes ](/unit1/Feb_26_wireframes.md)
  - [Sunday Presentation Slides](https://docs.google.com/a/mozilla.com/presentation/d/1-Ks6Cd87tmEQyJVqqCzxCBH8ZYmUV-NdVJLI5kD8zwo/edit?usp=sharing)
  - [List of other MisinfoCon presentations](https://hackpad.com/Presentations-list-HEfQO6oBc79)
- Feb 23, 2017: Drafts [notes](https://docs.google.com/a/nucleuslearningnetwork.org/document/d/1YczOCZ9QrWhbbqqNkX57JwtOrbS5xdSsa7rgeyi4W-c/edit?usp=sharing) for Lessons 2 & 3
- Feb 17, 2017: Draft product spec and curriculum for Lesson 1 (Legit-o-Meter) complete
  - [Lesson Plan & Worksheet](https://docs.google.com/document/d/1fiA4r5OKVco8b9Gjk7QW4ZlxalsWK4_IpfWV1PITzK4/edit?usp=sharing)
  - [Web App Product Brief](https://docs.google.com/document/d/1wjEQ1J8NYLxTLQ2HNXMtlJkVIZa60feeGEWoNS80ZLo/edit?usp=sharing)
- Feb 9, 2017: Fake the News team met for brainstorming on the three lesson. Sarah (Nucleus Learning Network) is tasked with creating a Curriculum Outline Draft and Mateo (Open Austin) is tasked with creating a Design Brief for the Legit-o-Meter web app.

_These are all working titles_

### Lesson #1: Legit-o-Meter

The goal of Lesson 1 is to give students the tools to examine a web article's credibility. The Fake the News team will develop a web app version of the [Kraken the Code Web Literacy Exercise](https://mozilla.github.io/webmaker-curriculum/WebLiteracyBasics-I/session01-kraken.html).

- More info on the Web App development progress on [Github](https://github.com/civicparty/legitometer).
- [Legit-o-Meter Lesson Plan](https://docs.google.com/document/d/1fiA4r5OKVco8b9Gjk7QW4ZlxalsWK4_IpfWV1PITzK4/edit?usp=sharing)

### Lesson #2: Rewriting History

The goal of Lesson 2 is to help students understand the origins and consequences of fake news using historical examples. By the end of the lesson, they will understand what motivates this ecosystem and how money, propoganda, misinformation, and political bias influence the content we see online.

### Lesson #3: Run the Presses

The goal of the Lesson 3 is to put students in the seat of the important roles at a news publishing organization. As a journalist, what goes into writing and article? As an Editor, what articles do you choose run with and why?


text:
package fun.lang;

import java.util.Iterator;

import fun.runtime.Context;

/**
 * A BinaryExpression is a construction based on a binary operator.
 *
 * @author Michael St. Hippolyte
 * @version $Revision: 1.12 $
 */

public class BinaryExpression extends Expression {

    public BinaryExpression() {
        super();
    }

    private BinaryExpression(BinaryExpression expression) {
        super(expression);
    }

    public Object generateData(Context context, Definition def) throws Redirection {
        // a binary expression can have multiple instances of a binary
        // operator, e.g. a + b + c is parsed into a single
        // BinaryExpression which owns three values and two instances of
        // AddOperator.
        int len = getNumChildren();
        ValueSource val = (ValueSource) getChild(0);
        for (int i = 1; i < len - 1; i += 2) {
            BinaryOperator op = (BinaryOperator) getChild(i);
            ValueSource nextVal = (ValueSource) getChild(i + 1);
            if (nextVal instanceof ForStatement) {
                Iterator<Construction> vals = ((ForStatement) nextVal).generateConstructions(context).iterator();
                while (vals.hasNext()) {
                    val = op.operate(val, vals.next(), context);
                }

            } else {
                val = op.operate(val, nextVal, context);
            }
        }
        return val;

//        Value val = getChildValue(context, 0);
//        for (int i = 1; i < len - 1; i += 2) {
//            BinaryOperator op = (BinaryOperator) getChild(i);
//            Value nextVal = new DeferredValue((ValueSource) getChild(i + 1), context);
//            val = op.operate(val, nextVal);
//        }
//        return val;
    }

    public Type getType(Context context, boolean generate) {
        int len = getNumChildren();
        Type type = getChildType(context, generate, 0);
        for (int i = 1; i < len - 1; i += 2) {
            BinaryOperator op = (BinaryOperator) getChild(i);
            type = op.getResultType(type, getChildType(context, generate, i + 1), context);
        }
        return type;
    }

    public Expression resolveExpression(Context context) {
        BinaryExpression resolvedExpression = new BinaryExpression(this);
        resolvedExpression.resolveChildrenInPlace(context);
        return resolvedExpression;
    }
}


text:
package com.twitter.finagle.mysql

sealed trait IsolationLevel {
  private[mysql] val name: String
}

/**
 * MySQL Isolation Levels. Used to override the SESSION or GLOBAL isolation level when
 * executing transactions.
 *
 * @see [[com.twitter.finagle.mysql.Transactions]]
 * @see [[https://dev.mysql.com/doc/refman/5.7/en/innodb-transaction-isolation-levels.html]]
 */
object IsolationLevel {

  case object ReadUncommitted extends IsolationLevel {
    val name = "READ UNCOMMITTED"
  }

  case object ReadCommitted extends IsolationLevel {
    val name = "READ COMMITTED"
  }

  case object RepeatableRead extends IsolationLevel {
    val name = "REPEATABLE READ"
  }

  case object Serializable extends IsolationLevel {
    val name = "SERIALIZABLE"
  }

}


text:
<?php

namespace Weaver;

use Danack\Code\Generator\DocBlockGenerator;
use Danack\Code\Generator\MethodGenerator;
use Danack\Code\Generator\ParameterGenerator;
use Danack\Code\Generator\PropertyGenerator;
use Danack\Code\Reflection\MethodReflection;
use Danack\Code\Reflection\ClassReflection;

/**
 * Class SingleClassWeaveGenerator
 * Base class for the ImplementWeaveGenerator, ExtendWeaveGenerator and
 * LazyWeaveGenerator
 * @package Weaver
 */
abstract class SingleClassWeaveGenerator {

    /**
     * @var \Danack\Code\Generator\ClassGenerator
     */
    protected $generator;

    /**
     * @var ClassReflection
     */
    protected $sourceClassReflection;

    /**
     * @var ClassReflection
     */
    protected $decoratorReflection;

    /**
     * @return string
     */
    function getNamespaceName() {
        return $this->sourceClassReflection->getNamespaceName();
    }

    /**
     * * Generates a name that indicates what the class is composed of.
     * e.g. A DB class decorated with Timer would be TimerXDB
     *
     * @return string
     */
    function generateWeavedName() {
        return $this->decoratorReflection->getShortName()."X".$this->sourceClassReflection->getShortName();
    }

    /**
     * addPropertiesAndConstantsFromReflection - does what it's name says.
     *
     * @param ClassReflection $classReflection
     * @internal param $originalSourceClass
     */
    function addPropertiesAndConstantsFromReflection(ClassReflection $classReflection ) {
        $constants = $classReflection->getConstants();
        foreach ($constants as $name => $value) {
            $this->generator->addProperty($name, $value, PropertyGenerator::FLAG_CONSTANT);
        }

        $properties = $classReflection->getProperties();
        foreach ($properties as $property) {
            $newProperty = PropertyGenerator::fromReflection($property);
            $newProperty->setVisibility(\Danack\Code\Generator\AbstractMemberGenerator::FLAG_PRIVATE);
            $this->generator->addPropertyFromGenerator($newProperty);
        }
    }

    /**
     * Directly add the methods from the decorating class. They are not modified.
     * The 'special' functions __construct, __prototype and __extend are not copied
     * as they are instead used to generate decorated methods.
     *
     * @return null|MethodReflection
     */
    function addDecoratorMethods() {
        $methods = $this->decoratorReflection->getMethods();

        foreach ($methods as $method) {
            $name = $method->getName();

            if ($name === '__construct' || $name === '__prototype' || $name == '__extend') {
                continue;
            }

            $methodGenerator = MethodGenerator::fromReflection($method);
            $this->generator->addMethodFromGenerator($methodGenerator);
        }
    }

    /**
     * @return string
     */
    function getFQCN() {
        $namespace = $this->getNamespaceName();
        $classname = $this->generateWeavedName();

        $return = $classname;

        if (strlen($namespace)) {
            $return = $namespace.'\\'.$return;
        }

        return $return;
    }
}