text:
#ifndef MacroAssemblerX86_64_h
#define MacroAssemblerX86_64_h

#if ENABLE(ASSEMBLER) && CPU(X86_64)

#include "MacroAssemblerX86Common.h"

#define REPTACH_OFFSET_CALL_R11 3

namespace JSC {

class MacroAssemblerX86_64 : public MacroAssemblerX86Common {
public:
    static const Scale ScalePtr = TimesEight;

    using MacroAssemblerX86Common::add32;
    using MacroAssemblerX86Common::and32;
    using MacroAssemblerX86Common::branchAdd32;
    using MacroAssemblerX86Common::or32;
    using MacroAssemblerX86Common::sub32;
    using MacroAssemblerX86Common::load32;
    using MacroAssemblerX86Common::store32;
    using MacroAssemblerX86Common::store8;
    using MacroAssemblerX86Common::call;
    using MacroAssemblerX86Common::jump;
    using MacroAssemblerX86Common::addDouble;
    using MacroAssemblerX86Common::loadDouble;
    using MacroAssemblerX86Common::convertInt32ToDouble;

    void add32(TrustedImm32 imm, AbsoluteAddress address)
    {
        move(TrustedImmPtr(address.m_ptr), scratchRegister);
        add32(imm, Address(scratchRegister));
    }

    void and32(TrustedImm32 imm, AbsoluteAddress address)
    {
        move(TrustedImmPtr(address.m_ptr), scratchRegister);
        and32(imm, Address(scratchRegister));
    }

    void add32(AbsoluteAddress address, RegisterID dest)
    {
        move(TrustedImmPtr(address.m_ptr), scratchRegister);
        add32(Address(scratchRegister), dest);
    }

    void or32(TrustedImm32 imm, AbsoluteAddress address)
    {
        move(TrustedImmPtr(address.m_ptr), scratchRegister);
        or32(imm, Address(scratchRegister));
    }

    void or32(RegisterID reg, AbsoluteAddress address)
    {
        move(TrustedImmPtr(address.m_ptr), scratchRegister);
        or32(reg, Address(scratchRegister));
    }

    void sub32(TrustedImm32 imm, AbsoluteAddress address)
    {
        move(TrustedImmPtr(address.m_ptr), scratchRegister);
        sub32(imm, Address(scratchRegister));
    }

    void load32(const void* address, RegisterID dest)
    {
        if (dest == X86Registers::eax)
            m_assembler.movl_mEAX(address);
        else {
            move(TrustedImmPtr(address), dest);
            load32(dest, dest);
        }
    }

    void addDouble(AbsoluteAddress address, FPRegisterID dest)
    {
        move(TrustedImmPtr(address.m_ptr), scratchRegister);
        m_assembler.addsd_mr(0, scratchRegister, dest);
    }

    void convertInt32ToDouble(TrustedImm32 imm, FPRegisterID dest)
    {
        move(imm, scratchRegister);
        m_assembler.cvtsi2sd_rr(scratchRegister, dest);
    }

    void store32(TrustedImm32 imm, void* address)
    {
        move(TrustedImmPtr(address), scratchRegister);
        store32(imm, scratchRegister);
    }

    void store8(TrustedImm32 imm, void* address)
    {
        move(TrustedImmPtr(address), scratchRegister);
        store8(imm, Address(scratchRegister));
    }

    Call call()
    {
        DataLabelPtr label = moveWithPatch(TrustedImmPtr(0), scratchRegister);
        Call result = Call(m_assembler.call(scratchRegister), Call::Linkable);
        ASSERT_UNUSED(label, differenceBetween(label, result) == REPTACH_OFFSET_CALL_R11);
        return result;
    }

    // Address is a memory location containing the address to jump to
    void jump(AbsoluteAddress address)
    {
        move(TrustedImmPtr(address.m_ptr), scratchRegister);
        jump(Address(scratchRegister));
    }

    Call tailRecursiveCall()
    {
        DataLabelPtr label = moveWithPatch(TrustedImmPtr(0), scratchRegister);
        Jump newJump = Jump(m_assembler.jmp_r(scratchRegister));
        ASSERT_UNUSED(label, differenceBetween(label, newJump) == REPTACH_OFFSET_CALL_R11);
        return Call::fromTailJump(newJump);
    }

    Call makeTailRecursiveCall(Jump oldJump)
    {
        oldJump.link(this);
        DataLabelPtr label = moveWithPatch(TrustedImmPtr(0), scratchRegister);
        Jump newJump = Jump(m_assembler.jmp_r(scratchRegister));
        ASSERT_UNUSED(label, differenceBetween(label, newJump) == REPTACH_OFFSET_CALL_R11);
        return Call::fromTailJump(newJump);
    }

    Jump branchAdd32(ResultCondition cond, TrustedImm32 src, AbsoluteAddress dest)
    {
        move(TrustedImmPtr(dest.m_ptr), scratchRegister);
        add32(src, Address(scratchRegister));
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    void add64(RegisterID src, RegisterID dest)
    {
        m_assembler.addq_rr(src, dest);
    }

    void add64(Address src, RegisterID dest)
    {
        m_assembler.addq_mr(src.offset, src.base, dest);
    }

    void add64(AbsoluteAddress src, RegisterID dest)
    {
        move(TrustedImmPtr(src.m_ptr), scratchRegister);
        add64(Address(scratchRegister), dest);
    }

    void add64(TrustedImm32 imm, RegisterID srcDest)
    {
        m_assembler.addq_ir(imm.m_value, srcDest);
    }

    void add64(TrustedImm64 imm, RegisterID dest)
    {
        move(imm, scratchRegister);
        add64(scratchRegister, dest);
    }

    void add64(TrustedImm32 imm, RegisterID src, RegisterID dest)
    {
        m_assembler.leaq_mr(imm.m_value, src, dest);
    }

    void add64(TrustedImm32 imm, Address address)
    {
        m_assembler.addq_im(imm.m_value, address.offset, address.base);
    }

    void add64(TrustedImm32 imm, AbsoluteAddress address)
    {
        move(TrustedImmPtr(address.m_ptr), scratchRegister);
        add64(imm, Address(scratchRegister));
    }

    void and64(RegisterID src, RegisterID dest)
    {
        m_assembler.andq_rr(src, dest);
    }

    void and64(TrustedImm32 imm, RegisterID srcDest)
    {
        m_assembler.andq_ir(imm.m_value, srcDest);
    }

    void neg64(RegisterID dest)
    {
        m_assembler.negq_r(dest);
    }

    void or64(RegisterID src, RegisterID dest)
    {
        m_assembler.orq_rr(src, dest);
    }

    void or64(TrustedImm64 imm, RegisterID dest)
    {
        move(imm, scratchRegister);
        or64(scratchRegister, dest);
    }

    void or64(TrustedImm32 imm, RegisterID dest)
    {
        m_assembler.orq_ir(imm.m_value, dest);
    }

    void or64(RegisterID op1, RegisterID op2, RegisterID dest)
    {
        if (op1 == op2)
            move(op1, dest);
        else if (op1 == dest)
            or64(op2, dest);
        else {
            move(op2, dest);
            or64(op1, dest);
        }
    }

    void or64(TrustedImm32 imm, RegisterID src, RegisterID dest)
    {
        move(src, dest);
        or64(imm, dest);
    }

    void rotateRight64(TrustedImm32 imm, RegisterID srcDst)
    {
        m_assembler.rorq_i8r(imm.m_value, srcDst);
    }

    void sub64(RegisterID src, RegisterID dest)
    {
        m_assembler.subq_rr(src, dest);
    }

    void sub64(TrustedImm32 imm, RegisterID dest)
    {
        m_assembler.subq_ir(imm.m_value, dest);
    }

    void sub64(TrustedImm64 imm, RegisterID dest)
    {
        move(imm, scratchRegister);
        sub64(scratchRegister, dest);
    }

    void xor64(RegisterID src, RegisterID dest)
    {
        m_assembler.xorq_rr(src, dest);
    }

    void xor64(RegisterID src, Address dest)
    {
        m_assembler.xorq_rm(src, dest.offset, dest.base);
    }

    void xor64(TrustedImm32 imm, RegisterID srcDest)
    {
        m_assembler.xorq_ir(imm.m_value, srcDest);
    }

    void load64(ImplicitAddress address, RegisterID dest)
    {
        m_assembler.movq_mr(address.offset, address.base, dest);
    }

    void load64(BaseIndex address, RegisterID dest)
    {
        m_assembler.movq_mr(address.offset, address.base, address.index, address.scale, dest);
    }

    void load64(const void* address, RegisterID dest)
    {
        if (dest == X86Registers::eax)
            m_assembler.movq_mEAX(address);
        else {
            move(TrustedImmPtr(address), dest);
            load64(dest, dest);
        }
    }

    DataLabel32 load64WithAddressOffsetPatch(Address address, RegisterID dest)
    {
        padBeforePatch();
        m_assembler.movq_mr_disp32(address.offset, address.base, dest);
        return DataLabel32(this);
    }

    DataLabelCompact load64WithCompactAddressOffsetPatch(Address address, RegisterID dest)
    {
        padBeforePatch();
        m_assembler.movq_mr_disp8(address.offset, address.base, dest);
        return DataLabelCompact(this);
    }

    void store64(RegisterID src, ImplicitAddress address)
    {
        m_assembler.movq_rm(src, address.offset, address.base);
    }

    void store64(RegisterID src, BaseIndex address)
    {
        m_assembler.movq_rm(src, address.offset, address.base, address.index, address.scale);
    }

    void store64(RegisterID src, void* address)
    {
        if (src == X86Registers::eax)
            m_assembler.movq_EAXm(address);
        else {
            move(TrustedImmPtr(address), scratchRegister);
            store64(src, scratchRegister);
        }
    }

    void store64(TrustedImm64 imm, ImplicitAddress address)
    {
        move(imm, scratchRegister);
        store64(scratchRegister, address);
    }

    void store64(TrustedImm64 imm, BaseIndex address)
    {
        move(imm, scratchRegister);
        m_assembler.movq_rm(scratchRegister, address.offset, address.base, address.index, address.scale);
    }

    DataLabel32 store64WithAddressOffsetPatch(RegisterID src, Address address)
    {
        padBeforePatch();
        m_assembler.movq_rm_disp32(src, address.offset, address.base);
        return DataLabel32(this);
    }

    void move64ToDouble(RegisterID src, FPRegisterID dest)
    {
        m_assembler.movq_rr(src, dest);
    }

    void moveDoubleTo64(FPRegisterID src, RegisterID dest)
    {
        m_assembler.movq_rr(src, dest);
    }

    void compare64(RelationalCondition cond, RegisterID left, TrustedImm32 right, RegisterID dest)
    {
        if (((cond == Equal) || (cond == NotEqual)) && !right.m_value)
            m_assembler.testq_rr(left, left);
        else
            m_assembler.cmpq_ir(right.m_value, left);
        m_assembler.setCC_r(x86Condition(cond), dest);
        m_assembler.movzbl_rr(dest, dest);
    }

    void compare64(RelationalCondition cond, RegisterID left, RegisterID right, RegisterID dest)
    {
        m_assembler.cmpq_rr(right, left);
        m_assembler.setCC_r(x86Condition(cond), dest);
        m_assembler.movzbl_rr(dest, dest);
    }

    Jump branch64(RelationalCondition cond, RegisterID left, RegisterID right)
    {
        m_assembler.cmpq_rr(right, left);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branch64(RelationalCondition cond, RegisterID left, TrustedImm64 right)
    {
        if (((cond == Equal) || (cond == NotEqual)) && !right.m_value) {
            m_assembler.testq_rr(left, left);
            return Jump(m_assembler.jCC(x86Condition(cond)));
        }
        move(right, scratchRegister);
        return branch64(cond, left, scratchRegister);
    }

    Jump branch64(RelationalCondition cond, RegisterID left, Address right)
    {
        m_assembler.cmpq_mr(right.offset, right.base, left);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branch64(RelationalCondition cond, AbsoluteAddress left, RegisterID right)
    {
        move(TrustedImmPtr(left.m_ptr), scratchRegister);
        return branch64(cond, Address(scratchRegister), right);
    }

    Jump branch64(RelationalCondition cond, Address left, RegisterID right)
    {
        m_assembler.cmpq_rm(right, left.offset, left.base);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branch64(RelationalCondition cond, Address left, TrustedImm64 right)
    {
        move(right, scratchRegister);
        return branch64(cond, left, scratchRegister);
    }

    Jump branchTest64(ResultCondition cond, RegisterID reg, RegisterID mask)
    {
        m_assembler.testq_rr(reg, mask);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branchTest64(ResultCondition cond, RegisterID reg, TrustedImm32 mask = TrustedImm32(-1))
    {
        // if we are only interested in the low seven bits, this can be tested with a testb
        if (mask.m_value == -1)
            m_assembler.testq_rr(reg, reg);
        else if ((mask.m_value & ~0x7f) == 0)
            m_assembler.testb_i8r(mask.m_value, reg);
        else
            m_assembler.testq_i32r(mask.m_value, reg);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    void test64(ResultCondition cond, RegisterID reg, TrustedImm32 mask, RegisterID dest)
    {
        if (mask.m_value == -1)
            m_assembler.testq_rr(reg, reg);
        else if ((mask.m_value & ~0x7f) == 0)
            m_assembler.testb_i8r(mask.m_value, reg);
        else
            m_assembler.testq_i32r(mask.m_value, reg);
        set32(x86Condition(cond), dest);
    }

    void test64(ResultCondition cond, RegisterID reg, RegisterID mask, RegisterID dest)
    {
        m_assembler.testq_rr(reg, mask);
        set32(x86Condition(cond), dest);
    }

    Jump branchTest64(ResultCondition cond, AbsoluteAddress address, TrustedImm32 mask = TrustedImm32(-1))
    {
        load64(address.m_ptr, scratchRegister);
        return branchTest64(cond, scratchRegister, mask);
    }

    Jump branchTest64(ResultCondition cond, Address address, TrustedImm32 mask = TrustedImm32(-1))
    {
        if (mask.m_value == -1)
            m_assembler.cmpq_im(0, address.offset, address.base);
        else
            m_assembler.testq_i32m(mask.m_value, address.offset, address.base);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branchTest64(ResultCondition cond, Address address, RegisterID reg)
    {
        m_assembler.testq_rm(reg, address.offset, address.base);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branchTest64(ResultCondition cond, BaseIndex address, TrustedImm32 mask = TrustedImm32(-1))
    {
        if (mask.m_value == -1)
            m_assembler.cmpq_im(0, address.offset, address.base, address.index, address.scale);
        else
            m_assembler.testq_i32m(mask.m_value, address.offset, address.base, address.index, address.scale);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branchAdd64(ResultCondition cond, TrustedImm32 imm, RegisterID dest)
    {
        add64(imm, dest);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branchAdd64(ResultCondition cond, RegisterID src, RegisterID dest)
    {
        add64(src, dest);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branchSub64(ResultCondition cond, TrustedImm32 imm, RegisterID dest)
    {
        sub64(imm, dest);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branchSub64(ResultCondition cond, RegisterID src, RegisterID dest)
    {
        sub64(src, dest);
        return Jump(m_assembler.jCC(x86Condition(cond)));
    }

    Jump branchSub64(ResultCondition cond, RegisterID src1, TrustedImm32 src2, RegisterID dest)
    {
        move(src1, dest);
        return branchSub64(cond, src2, dest);
    }

    ConvertibleLoadLabel convertibleLoadPtr(Address address, RegisterID dest)
    {
        ConvertibleLoadLabel result = ConvertibleLoadLabel(this);
        m_assembler.movq_mr(address.offset, address.base, dest);
        return result;
    }

    DataLabelPtr moveWithPatch(TrustedImmPtr initialValue, RegisterID dest)
    {
        padBeforePatch();
        m_assembler.movq_i64r(initialValue.asIntptr(), dest);
        return DataLabelPtr(this);
    }

    Jump branchPtrWithPatch(RelationalCondition cond, RegisterID left, DataLabelPtr& dataLabel, TrustedImmPtr initialRightValue = TrustedImmPtr(0))
    {
        dataLabel = moveWithPatch(initialRightValue, scratchRegister);
        return branch64(cond, left, scratchRegister);
    }

    Jump branchPtrWithPatch(RelationalCondition cond, Address left, DataLabelPtr& dataLabel, TrustedImmPtr initialRightValue = TrustedImmPtr(0))
    {
        dataLabel = moveWithPatch(initialRightValue, scratchRegister);
        return branch64(cond, left, scratchRegister);
    }

    DataLabelPtr storePtrWithPatch(TrustedImmPtr initialValue, ImplicitAddress address)
    {
        DataLabelPtr label = moveWithPatch(initialValue, scratchRegister);
        store64(scratchRegister, address);
        return label;
    }

    using MacroAssemblerX86Common::branchTest8;
    Jump branchTest8(ResultCondition cond, ExtendedAddress address, TrustedImm32 mask = TrustedImm32(-1))
    {
        TrustedImmPtr addr(reinterpret_cast<void*>(address.offset));
        MacroAssemblerX86Common::move(addr, scratchRegister);
        return MacroAssemblerX86Common::branchTest8(cond, BaseIndex(scratchRegister, address.base, TimesOne), mask);
    }

    Jump branchTest8(ResultCondition cond, AbsoluteAddress address, TrustedImm32 mask = TrustedImm32(-1))
    {
        MacroAssemblerX86Common::move(TrustedImmPtr(address.m_ptr), scratchRegister);
        return MacroAssemblerX86Common::branchTest8(cond, Address(scratchRegister), mask);
    }

    static bool supportsFloatingPoint() { return true; }
    // See comment on MacroAssemblerARMv7::supportsFloatingPointTruncate()
    static bool supportsFloatingPointTruncate() { return true; }
    static bool supportsFloatingPointSqrt() { return true; }
    static bool supportsFloatingPointAbs() { return true; }

    static FunctionPtr readCallTarget(CodeLocationCall call)
    {
        return FunctionPtr(X86Assembler::readPointer(call.dataLabelPtrAtOffset(-REPTACH_OFFSET_CALL_R11).dataLocation()));
    }

    static RegisterID scratchRegisterForBlinding() { return scratchRegister; }

    static bool canJumpReplacePatchableBranchPtrWithPatch() { return true; }

    static CodeLocationLabel startOfBranchPtrWithPatchOnRegister(CodeLocationDataLabelPtr label)
    {
        const int rexBytes = 1;
        const int opcodeBytes = 1;
        const int immediateBytes = 8;
        const int totalBytes = rexBytes + opcodeBytes + immediateBytes;
        ASSERT(totalBytes >= maxJumpReplacementSize());
        return label.labelAtOffset(-totalBytes);
    }

    static CodeLocationLabel startOfPatchableBranchPtrWithPatchOnAddress(CodeLocationDataLabelPtr label)
    {
        return startOfBranchPtrWithPatchOnRegister(label);
    }

    static void revertJumpReplacementToPatchableBranchPtrWithPatch(CodeLocationLabel instructionStart, Address, void* initialValue)
    {
        X86Assembler::revertJumpTo_movq_i64r(instructionStart.executableAddress(), reinterpret_cast<intptr_t>(initialValue), scratchRegister);
    }

    static void revertJumpReplacementToBranchPtrWithPatch(CodeLocationLabel instructionStart, RegisterID, void* initialValue)
    {
        X86Assembler::revertJumpTo_movq_i64r(instructionStart.executableAddress(), reinterpret_cast<intptr_t>(initialValue), scratchRegister);
    }

private:
    friend class LinkBuffer;
    friend class RepatchBuffer;

    static void linkCall(void* code, Call call, FunctionPtr function)
    {
        if (!call.isFlagSet(Call::Near))
            X86Assembler::linkPointer(code, call.m_label.labelAtOffset(-REPTACH_OFFSET_CALL_R11), function.value());
        else
            X86Assembler::linkCall(code, call.m_label, function.value());
    }

    static void repatchCall(CodeLocationCall call, CodeLocationLabel destination)
    {
        X86Assembler::repatchPointer(call.dataLabelPtrAtOffset(-REPTACH_OFFSET_CALL_R11).dataLocation(), destination.executableAddress());
    }

    static void repatchCall(CodeLocationCall call, FunctionPtr destination)
    {
        X86Assembler::repatchPointer(call.dataLabelPtrAtOffset(-REPTACH_OFFSET_CALL_R11).dataLocation(), destination.executableAddress());
    }

};

} // namespace JSC

#endif // ENABLE(ASSEMBLER)

#endif // MacroAssemblerX86_64_h


text:
<nav-bar></nav-bar>
<router-outlet></router-outlet>

{{count |async}}

<button (click) ="increment()"
        class ="btn btn-primary">
         Incrementor
</button>

redpajama_set_name: RedPajamaGithub


text:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

// id3tag struct for use throughout this program.
struct id3tag {
		char identifier[3];
		char title[30];
		char artist[30];
		char album[30];
		char year[4];
		char comment[28];
		char separator;
		unsigned char track;
		unsigned char genre;
};

// Function prototypes
void print_tag(struct id3tag *tag_p);
int read_tag(char *path,struct id3tag *tag_p);
int write_tag(int argument_count, char **arguments,struct id3tag *tag_p);

// Simply prints, in a formatted manner, the contents of an id3tag struct.
void print_tag(struct id3tag *tag_p) {
	printf("Title: %-30.30s\n",tag_p->title);
	printf("Artist: %-30.30s\n",tag_p->artist);
	printf("Album: %-30.30s\n",tag_p->album);
	printf("Year: %-4.4s\n",tag_p->year);
	printf("Comment: %-28.28s\n",tag_p->comment);
	printf("Track number: %d\n",tag_p->track);
	printf("Genre: %d\n\n",tag_p->genre);
}

// This function simply reads the tags in a file. If there are none, it says so. If the file is incorrect, it returns 1, else returns 0.
int read_tag(char *path,struct id3tag *tag_p) {
	FILE *musicfile;

	// Prints the filename entered by the user.
	printf("\nFilename: %s\n",path);

	// Open the file to read.
	musicfile = fopen(path,"rb");

	// Return 1 if the file was empty or somehow otherwise bad.
	if (musicfile == NULL)
		return(1);

	// Go to 128 bytes from the end of the file, where the tag data should be if it exists.
	fseek(musicfile,-128L,SEEK_END);

	// Read the last 128 bytes of the file into the tag struct. Note that the tag struct is simply treated as a location in memory.
	fread(tag_p,1,128,musicfile);
	fclose(musicfile);

    if (strncmp(tag_p->identifier,"TAG",3)==0) // If the tag contains the identifier, then it has a tag, and it can be printed.
		print_tag(tag_p);
	else { // Tag did not have the identifier. That is to say, the location in memory did not containt TAG
		printf("There was no ID3v1.1 tag in the specified file.\n");
		return 2; // Return 2 means that it had no ID3v1.1 tag.
	}

	// Return 0 if everything went fine.
	return 0;
}

int write_tag(int argument_count, char **arguments,struct id3tag *tag_p) {
	int read_return; // Stores what is returned from the read_tag function.
	int counter;
	FILE *write_file; // FILE for writing. Same as the file for reading, but reopened specifically to append.

	// Print the original ID3v1.1 tag, if there is one.
	printf("\nOriginal ID3v1.1 tag:\n");
	read_return = read_tag(arguments[1],tag_p);

	// Return 1 if the file was empty or somehow otherwise bad.
	if (read_return == 1)
		return 1;
	else if (read_return == 0) { // If the file read correctly, and it had an existing ID3v1.1 tag.
		// Loop to check to see if there are tags to be set. If the user enters an incorrect switch, such as -FOOBAR, that switch and the data that follows it is simply ignored.
		for (counter = 2;counter < argument_count;counter++) {
			if ((strcmp(arguments[counter],"-TITLE")) == 0)
				strncpy(tag_p->title,arguments[++counter],30);
			else if ((strcmp(arguments[counter],"-ARTIST")) == 0)
				strncpy(tag_p->artist,arguments[++counter],30);
			else if ((strcmp(arguments[counter],"-ALBUM")) == 0)
				strncpy(tag_p->album,arguments[++counter],30);
			else if ((strcmp(arguments[counter],"-YEAR")) == 0)
				strncpy(tag_p->year,arguments[++counter],4);
			else if ((strcmp(arguments[counter],"-COMMENT")) == 0)
				strncpy(tag_p->comment,arguments[++counter],28);
			else if ((strcmp(arguments[counter],"-TRACK")) == 0)
				tag_p->track = atoi(arguments[++counter]);
		}

		// Open file for reading and writing.
		write_file = fopen(arguments[1],"r+b");

		// Verify it is not an empty file. Perhaps redundant, but not harmful.
		if (write_file == NULL)
			return(1);

		// Seek to the position of the existing tag in the file.
		fseek(write_file,-128L,SEEK_END);

		// Write the tag to the file in one go. Writes as a byte stream. Then closes the file.
		fwrite(tag_p,1,128,write_file);
		fclose(write_file);
	}
	else if (read_return == 2) { // If the file read correctly, but it did not have an existing ID3v1.1 tag.
		// Set tag struct to all null bytes initially. That way if some tag is not set, then it is just full of null.
		// There is probably a better way to do this with memset or something like that. We haven't learned that yet...
		strncpy(tag_p->identifier,"TAG",3);
		strncpy(tag_p->title,"",30);
		strncpy(tag_p->artist,"",30);
		strncpy(tag_p->album,"",30);
		strncpy(tag_p->year,"",4);
		strncpy(tag_p->comment,"",28);
		tag_p->separator = '\0';
		tag_p->track = atoi("");
		tag_p->genre = atoi("0");

		// Loop to check to see if there are tags to be set. If the user enters an incorrect switch, such as -FOOBAR, that switch and the data that follows it is simply ignored.
		for (counter = 2;counter < argument_count;counter++) {
			if ((strcmp(arguments[counter],"-TITLE")) == 0) // If the switch is for the title, grab the next data, and set it to that.
				strncpy(tag_p->title,arguments[++counter],30);
			else if ((strcmp(arguments[counter],"-ARTIST")) == 0) // If the switch is for the artist, grab the next data, and set it to that.
				strncpy(tag_p->artist,arguments[++counter],30);
			else if ((strcmp(arguments[counter],"-ALBUM")) == 0) // If the switch is for the album, grab the next data, and set it to that.
				strncpy(tag_p->album,arguments[++counter],30);
			else if ((strcmp(arguments[counter],"-YEAR")) == 0) // If the switch is for the year, grab the next data, and set it to that.
				strncpy(tag_p->year,arguments[++counter],4);
			else if ((strcmp(arguments[counter],"-COMMENT")) == 0) // If the switch is for the comment, grab the next data, and set it to that.
				strncpy(tag_p->comment,arguments[++counter],28);
			else if ((strcmp(arguments[counter],"-TRACK")) == 0) // If the switch is for the track number, grab the next data, and set it to that.
				tag_p->track = atoi(arguments[++counter]);
		}

		// Open file for apending ONLY.
		write_file = fopen(arguments[1],"ab");

		// Verify it is not an empty file. Perhaps redundant, but not harmful.
		if (write_file == NULL)
			return(1);

		// Write the tag to the end of the file in one go. Writes as a byte stream. Then closes the file.
		fwrite(tag_p,1,128,write_file);
		fclose(write_file);
	}

	// Print out the new ID3v1.1 data for the user to see.
	printf("New ID3v1.1 tag:\n");
	print_tag(tag_p);

	// Return 0 if everything went fine.
	return 0;
}

// Main function.
int main (int argc, char *argv[]) {
	/*  ID3v1.1 standard information:
		Offset	length	description
		0		3		"TAG" identifier string
		3		30		Song title string
		33		30		Artist string
		63		30		Album string
		93		4		Year string
		97		28		Comment string
		125		1		A one-byte separator (always 0)
		126		1		Track number byte
		127		1		Genre identifier byte
	*/

	// Variable declaration.
	struct id3tag the_tag;
	int temp_return;

	// Initially set temp_return equal to 0.
	temp_return = 0;

	if (argc == 1) { // If the user does not enter any arguments. WILL CHANGE PROGRAMNAME LATER.
		printf("You entered no filename!\nCorrect usage:\nPROGRAMNAME FILE_NAME.EXT\n\tDisplay current ID3v1.1 data in a file\nPROGRAMNAME FILE_NAME.EXT -SWITCH NEW_DATA ...\n\tEither changes the existing ID3v1.1 data, or creates a new tag with the specified data.\n");
		printf("\nAvailable switches:");
		printf("\n-TITLE \"TITLE_DATA\"\t-\tSets the title to the specified data");
		printf("\n-ARTIST \"ARTIST_DATA\"\t-\tSets the artist to the specified data");
		printf("\n-ALBUM \"ALBUM_DATA\"\t-\tSets the album to the specified data");
		printf("\n-YEAR \"YEAR_DATA\"\t-\tSets the year to the specified data");
		printf("\n-COMMENT \"COMMENT_DATA\"\t-\tSets the comment to the specified data");
		printf("\n-TRACK \"TRACK_NUMBER\"\t-\tSets the track to the specified number\n\n");
	}
	else if (argc == 2) // If the user only enters a filename, just read out the tag.
		temp_return = read_tag(argv[1],&the_tag);
	else if ((argc % 2) == 1) // If the user enters an invalid number of arguments. 2 arguments for program name and filename, and then 2 more each for switches. If it is an odd number, they're missing something.
		printf("Invalid number of arguments!\n");
	else if ((argc % 2) == 0) // If the user enteres a correct number of arguments beyond just the program name and filename, then they want to write some tag data.
		temp_return = write_tag(argc,argv,&the_tag);

	if (temp_return == 1) // If the user entered an invalid filename.
		printf("You entered an invalid filename! :(\n");

	// Returns 0 if nothing went wrong with program execution.
	return 0;
}


text:
Board Reports
=============

Rationale
---------
.. figure:: ../_img/jira-report-select-agile.png
.. figure:: ../_img/jira-report-select-issueanalysis.png
.. figure:: ../_img/jira-report-select-mgmt.png
.. figure:: ../_img/jira-report-select-ng-scrum.png
.. figure:: ../_img/jira-report-select-ng-kanban.png

Burn-down Chart
---------------
.. figure:: ../_img/jira-report-burndownchart-storypoints-1.png
.. figure:: ../_img/jira-report-burndownchart-time-1.png
.. figure:: ../_img/jira-report-burndownchart-time-2.png

Burn-up Chart
-------------

Control Chart
-------------
.. figure:: ../_img/jira-report-controlchart-1.png
.. figure:: ../_img/jira-report-controlchart-2.png
.. figure:: ../_img/jira-report-controlchart-3.png

Cumulative Flow Diagram
-----------------------
.. figure:: ../_img/jira-report-cumulativeflowdiagram-1.png
.. figure:: ../_img/jira-report-cumulativeflowdiagram-2.gif
.. figure:: ../_img/jira-report-cumulativeflowdiagram-3.png
.. figure:: ../_img/jira-report-cumulativeflowdiagram-4.jpg
.. figure:: ../_img/jira-report-cumulativeflowdiagram-5.png
.. figure:: ../_img/jira-report-cumulativeflowdiagram-6.png
.. figure:: ../_img/jira-report-cumulativeflowdiagram-7.png
.. figure:: ../_img/jira-report-cumulativeflowdiagram-8.png
.. figure:: ../_img/jira-report-cumulativeflowdiagram-9.png
.. figure:: ../_img/jira-report-cumulativeflowdiagram-10.png

Epic Burndown
-------------
.. figure:: ../_img/jira-report-epicburndown-1.png
.. figure:: ../_img/jira-report-epicburndown-2.png

Epic Report
-----------
.. figure:: ../_img/jira-report-epicreport-1.png
.. figure:: ../_img/jira-report-epicreport-2.png

Release Burndown
----------------
.. figure:: ../_img/jira-report-releaseburndown-1.jpg
.. figure:: ../_img/jira-report-releaseburndown-2.png
.. figure:: ../_img/jira-report-releaseburndown-3.jpg
.. figure:: ../_img/jira-report-releaseburndown-3.png
.. figure:: ../_img/jira-report-releaseburndown-4.png
.. figure:: ../_img/jira-report-releaseburndown-5.png
.. figure:: ../_img/jira-report-releaseburndown-6.png
.. figure:: ../_img/jira-report-releaseburndown-7.png
.. figure:: ../_img/jira-report-releaseburndown-8.png
.. figure:: ../_img/jira-report-releaseburndown-9.png

Sprint Report
-------------

Velocity Chart
--------------
.. figure:: ../_img/jira-report-velocityreport-1.png
.. figure:: ../_img/jira-report-velocityreport-2.png

Version Report
--------------
.. figure:: ../_img/jira-report-versionreport-1.jpg
.. figure:: ../_img/jira-report-versionreport-2.png
.. figure:: ../_img/jira-report-versionreport-3.png

Version Burndown
----------------

Refine Reports
--------------

Time Tracking
-------------
.. figure:: ../_img/jira-report-timetracking-1.png
.. figure:: ../_img/jira-report-timetracking-2.png

Assignments
-----------

Board Usage Reports
^^^^^^^^^^^^^^^^^^^
#. Z menu u góry wybierz `Projects` -> Twój Projekt -> `Reports`
#. Przedyskutuj `Burndown Chart`
#. Przedyskutuj `Burnup Chart`
#. Przedyskutuj `Sprint Report`
#. Przedyskutuj `Velocity Chart`
#. Przedyskutuj `Cumulative Flow Diagram`
#. Przedyskutuj `Version Report`
#. Przedyskutuj `Epic Report`
#. Przedyskutuj `Control Chart`
#. Przedyskutuj `Epic Burndown`
#. Przedyskutuj `Release Burndown`
#. Przedyskutuj `Time Tracking Report`


text:
- `v::alnum()`
- `v::alnum(string $additionalChars)`

Validates alphanumeric characters from a-Z and 0-9.

```php
v::alnum()->validate('foo 123'); //true
```

A parameter for extra characters can be used:

```php
v::alnum('-')->validate('foo - 123'); //true
```

This validator allows whitespace, if you want to
remove them add `->noWhitespace()` to the chain:

```php
v::alnum()->noWhitespace->validate('foo 123'); //false
```

By default empty values are allowed, if you want
to invalidate them, add `->notEmpty()` to the chain:

```php
v::alnum()->notEmpty()->validate(''); //false
```

You can restrict case using the `->lowercase()` and
`->uppercase()` validators:

```php
v::alnum()->uppercase()->validate('aaa'); //false
```

Message template for this validator includes `{{additionalChars}}` as
the string of extra chars passed as the parameter.

***
See also:

  * [Alpha](Alpha.md)
  * [Digit](Digit.md)
  * [Consonant](Consonant.md)
  * [Vowel](Vowel.md)


text:
package org.encuestame.mvc.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.encuestame.core.config.EnMePlaceHolderConfigurer;
import org.encuestame.core.security.SecurityUtils;
import org.encuestame.core.util.EnMeUtils;
import org.encuestame.persistence.domain.tweetpoll.TweetPoll;
import org.encuestame.persistence.exception.EnMeExpcetion;
import org.encuestame.utils.web.frontEnd.WebMessage;
import org.encuestame.utils.web.frontEnd.WebMessage.WebInfoType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;

/**
 * Collection of utilities for Controller Views, Error Handlers only for Controller.
 * @author Picado, Juan juanATencuestame.org
 * @since Feb 08, 2013 06:31:20 AM
 */
@ControllerAdvice
public abstract class AbstractViewController extends AbstractBaseOperations{

    /**
    *
    */
   @Value("${encuestame.error.level}") protected Integer errorLevel;

   /**
    *
    */
   @Value("${encuestame.error.display_bugtracking}") protected Boolean bugTracking;

     /**
     * Log.
     */
    private Logger log = Logger.getLogger(this.getClass());

    /**
     * Customized error for {@link NoSuchRequestHandlingMethodException}.
     * @param ex {@link NoSuchRequestHandlingMethodException}.
     * @return {@link ResponseEntity}
     */
    @ExceptionHandler(NoSuchRequestHandlingMethodException.class)
    public ResponseEntity<String> handleNoSuchRequestHandlingMethodException(NoSuchRequestHandlingMethodException ex)   {
    	ex.printStackTrace();
       return this.errorManage(ex);
    }

    /**
     * Build a JSON error response based on the Exception message.
     * @param ex {@link Exception}
     * @return {@link ResponseEntity}
     */
    private ResponseEntity<String> errorManage(Exception ex) {
        ex.printStackTrace();
        log.debug("ServletRequestBindingException" + ex.getMessage());
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/json");
        final String text_error = ex.getMessage().replace("'", "");
        final String error = "{error : '" + text_error + "', success : null}";
        return new ResponseEntity<String>(error, headers, HttpStatus.BAD_REQUEST);
    }

    /**
     * Customized error for {@link ServletRequestBindingException}.
     * @param ex {@link ServletRequestBindingException}
     * @return {@link ResponseEntity}
     */
    @ExceptionHandler(ServletRequestBindingException.class)
    public ResponseEntity<String> handleServletRequestBindingException(ServletRequestBindingException ex)   {
    	ex.printStackTrace();
        return this.errorManage(ex);
    }

    /**
     * Handler for {@link AccessDeniedException}
     * @param ex exception
     * @return {@link ModelAndView}.
     */
    @SuppressWarnings("static-access")
    @ResponseStatus(value = HttpStatus.FORBIDDEN)
    @ExceptionHandler(AccessDeniedException.class)
    public ModelAndView handleException (final AccessDeniedException ex, HttpServletResponse httpResponse,
            HttpServletRequest request) {
      ex.printStackTrace();
       ModelAndView mav = new ModelAndView();
       mav.setViewName("tilesResolver");
       mav.setViewName("error/denied");
      final Map<String, Object> response = new HashMap<String, Object>();
      response.put("status", httpResponse.SC_FORBIDDEN);
      response.put("session", SecurityUtils.checkIsSessionIsExpired(getSecCtx().getAuthentication()));
      response.put(EnMeUtils.ANONYMOUS_USER, SecurityUtils.checkIsSessionIsAnonymousUser(getSecCtx().getAuthentication()));
      httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
      mav.addObject("error",  response);
      return mav;
    }

    /**
     *
     * @param ex
     * @param request
     * @return
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    ModelAndView handleException(EnMeExpcetion ex, HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("tilesResolver");
        mav.setViewName("error");
        ex.printStackTrace();
        WebMessage emptyError = new WebMessage(WebInfoType.ERROR, ex.getMessage(), ExceptionUtils.getFullStackTrace(ex),
                EnMePlaceHolderConfigurer.getIntegerProperty("encuestame.error.level"),
                EnMePlaceHolderConfigurer.getBooleanProperty("encuestame.error.display_bugtracking"));
        request.setAttribute("message", emptyError);
        return mav;
    }

    /**
     * In progress ENCUESTAME-676
     * @param modelMap
     * @param tweetPoll
     */
    public void setOgMetadataTweetPollInfo(
            final ModelMap modelMap,
            final TweetPoll tweetPoll,
            final HttpServletRequest request) {
        // https://developers.facebook.com/docs/sharing/best-practices?locale=es_LA
        modelMap.put("og_site_title", tweetPoll.getQuestion().getQuestion());
        modelMap.put("og_site_url_image", "");
        modelMap.put("og_site_name", EnMePlaceHolderConfigurer.getProperty("encuestame.site.name"));
        modelMap.put("og_site_description", EnMePlaceHolderConfigurer.getProperty("encuestame.site.description"));
        modelMap.put("fb_app_id", EnMePlaceHolderConfigurer.getProperty("facebook.api.id"));
        modelMap.put("og_site_type", EnMePlaceHolderConfigurer.getProperty("encuestame.site.type"));
        modelMap.put("og_locale", EnMePlaceHolderConfigurer.getProperty("encuestame.lang"));
        if (tweetPoll.getEditorOwner() != null) {
            modelMap.put("og_article_author", tweetPoll.getEditorOwner().getUsername());
        }
        modelMap.put("og_tags", ""); //FIXME: add hashtag list of the tweetpoll
    }
}


text:
nanogenmo issue: https://github.com/dariusk/NaNoGenMo-2014/issues/104

## Inspiration

I got to know about NaNoGenMo 2014 via Twitter. I first reworked an old script but then I got fed up with it (partly because it was written in PHP) and wanted to create something new (using JavaScript). I like generators which use existing text to create something new.

So I created a generator that is loosely inspired by the markov chain code from Hay Kranen from 2008. My generator reads an exisiting file, splits it on space, removes empty strings and numbers and creates a table containing all words with a list of all possible subsuquent words. After finishing this table, a for loop runs through this table, randomly choosing which word will be the next. After finishing, the output is shown.

## Usage
The two added text files are

* pg10.txt - the bible
* pg1041.txt - all sonnets by Shakespeare

```bash
$ node ./generator.js pg10.txt
```

## For the curious

First I had made a non-stream based version, and just for the matter of learning some extra stuff, I transformed the beginning of the script into using streams. Inspiration taken from:

* http://howtonode.org/coding-challenges-with-streams
* http://nodejs.org/api/stream.html#stream_object_mode

I have stripped all Gutenberg meta data from the text files so no traces of these will show up in the resulting text.

## License
MIT

## Contributors
* @_y_a_v_a_ - Vincent Bruijn


text:
package cn.cook.alex.chefgirl.ui.view;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.AbsListView;

import com.etsy.android.grid.StaggeredGridView;

import cn.cook.alex.chefgirl.dao.DBHelper;
import cn.cook.alex.chefgirl.dao.DataProvider;
import cn.cook.alex.chefgirl.utils.LogUtil;

/**
 * Created by alex on 15/2/14.
 */
public class PageStaggeredGridView extends StaggeredGridView implements AbsListView.OnScrollListener {

    private LoadingFooter mLoadingFooter;

    private OnLoadNextListener mLoadNextListener;

    private boolean canLoading = true;

    public PageStaggeredGridView(Context context) {
        super(context);
        init();
    }

    public PageStaggeredGridView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PageStaggeredGridView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {

        mLoadingFooter = new LoadingFooter(getContext());
        addFooterView(mLoadingFooter.getView());
        setOnScrollListener(this);
    }

    public void setLoadNextListener(OnLoadNextListener loadNextListener) {
        mLoadNextListener = loadNextListener;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        if (!canLoading) return;

        if (mLoadingFooter.getState() == LoadingFooter.State.Loading
                || mLoadingFooter.getState() == LoadingFooter.State.TheEnd) {
            return;
        }
        if (firstVisibleItem + visibleItemCount >= totalItemCount
                && totalItemCount != 0
                && totalItemCount != getHeaderViewsCount() + getFooterViewsCount()
                && mLoadNextListener != null) {
            mLoadingFooter.setState(LoadingFooter.State.Loading);
            if (mLoadingFooter.getState() != LoadingFooter.State.Loading)
                return;
            mLoadNextListener.onLoadNext();
        }
    }

    public void setState(LoadingFooter.State state) {
        mLoadingFooter.setState(state);
    }

    public void setState(LoadingFooter.State state, long delay) {
        mLoadingFooter.setState(state, delay);
    }

    public boolean isCanLoading() {
        return canLoading;
    }

    public void setCanLoading(boolean canLoading) {
        this.canLoading = canLoading;
    }
}


text:
<title>Test sandbox</title>

Test Sandbox

Simple test to check the sandbox that requires running a netcat session on the local network
and a web server that attempts to set and read a cookie. Saving this page as multiple
sandboxes can then allow testing if sandboxes are leaking referer and cookie information.


text:
package com.salesmanager.core.modules.utils;

import java.net.InetAddress;

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

import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.salesmanager.core.business.common.model.Address;

public class GeoLocationImpl implements GeoLocation {

	private DatabaseReader reader = null;
	private static final Logger LOGGER = LoggerFactory.getLogger( GeoLocationImpl.class );
	//@Value("${dbPath:classpath:/reference/GeoLite2-Country.mmdb}")
	//private Resource db;

	@Override
	public Address getAddress(String ipAddress) throws Exception {

			if(reader==null) {
				//if(db!=null) {
					//File file = db.getFile();
					try {
						java.io.InputStream inputFile = GeoLocationImpl.class.getClassLoader().getResourceAsStream("reference/GeoLite2-Country.mmdb");
						reader = new DatabaseReader.Builder(inputFile).build();
					} catch(Exception e) {
						LOGGER.error("Cannot instantiate IP database",e);
					}
				//}
			}

			Address address = new Address();

			CityResponse response = reader.city(InetAddress.getByName(ipAddress));

			address.setCountry(response.getCountry().getIsoCode());
			address.setPostalCode(response.getPostal().getCode());
			address.setZone(response.getMostSpecificSubdivision().getIsoCode());
			address.setCity(response.getCity().getName());

			return address;

	}

}


text:
@interface PodsDummy_Pods_RestFetcherExample : NSObject
@end
@implementation PodsDummy_Pods_RestFetcherExample
@end


text:
<?php

namespace Backend\Modules\Pages\Installer;

use Backend\Core\Installer\ModuleInstaller;
use Backend\Core\Engine\Model as BackendModel;
use Backend\Modules\Pages\Engine\Model as BackendPagesModel;
use Common\ModuleExtraType;
use SpoonFilter;

/**
 * Installer for the pages module
 */
class Installer extends ModuleInstaller
{
    /** @var array */
    private $extraIds;

    public function install(): void
    {
        $this->addModule('Pages');
        $this->importSQL(__DIR__ . '/Data/install.sql');
        $this->importLocale(__DIR__ . '/Data/locale.xml');
        $this->configureBackendNavigation();
        $this->configureBackendRights();
        $this->configureFrontendExtras();
        $this->configureFrontendPages();
    }

    private function configureBackendNavigation(): void
    {
        // Set navigation for "Pages"
        $this->setNavigation(null, $this->getModule(), 'pages/index', ['pages/add', 'pages/edit'], 2);

        // Set navigation for "Settings"
        $navigationSettingsId = $this->setNavigation(null, 'Settings');
        $navigationModulesId = $this->setNavigation($navigationSettingsId, 'Modules');
        $this->setNavigation($navigationModulesId, $this->getModule(), 'pages/settings');
    }

    private function configureBackendRights(): void
    {
        $this->setModuleRights(1, $this->getModule());

        $this->setActionRights(1, $this->getModule(), 'Add');
        $this->setActionRights(1, $this->getModule(), 'Delete');
        $this->setActionRights(1, $this->getModule(), 'Edit');
        $this->setActionRights(1, $this->getModule(), 'GetInfo'); // AJAX
        $this->setActionRights(1, $this->getModule(), 'Index');
        $this->setActionRights(1, $this->getModule(), 'Move'); // AJAX
        $this->setActionRights(1, $this->getModule(), 'RemoveUploadedFile'); // AJAX
        $this->setActionRights(1, $this->getModule(), 'Settings');
        $this->setActionRights(1, $this->getModule(), 'UploadFile'); // AJAX
    }

    /**
     * @todo: When we have Page entities, use DataFixtures instead of this method.
     */
    private function installExampleData(): void
    {
        // insert/get extra ids
        $extras = [];
        $extras['blog_block'] = $this->insertExtra('Blog', ModuleExtraType::block(), 'Blog');
        $extras['blog_widget_recent_comments'] = $this->insertExtra(
            'Blog',
            ModuleExtraType::widget(),
            'RecentComments',
            'RecentComments'
        );
        $extras['blog_widget_categories'] = $this->insertExtra(
            'Blog',
            ModuleExtraType::widget(),
            'Categories',
            'Categories'
        );
        $extras['blog_widget_archive'] = $this->insertExtra('Blog', ModuleExtraType::widget(), 'Archive', 'Archive');
        $extras['blog_widget_recent_articles_full'] = $this->insertExtra(
            'Blog',
            ModuleExtraType::widget(),
            'RecentArticlesFull',
            'RecentArticlesFull'
        );
        $extras['blog_widget_related_articles'] = $this->insertExtra(
            'Blog',
            ModuleExtraType::widget(),
            'RelatedArticles',
            'RelatedArticles'
        );
        $extras['blog_widget_recent_articles_list'] = $this->insertExtra(
            'Blog',
            ModuleExtraType::widget(),
            'RecentArticlesList',
            'RecentArticlesList'
        );
        if (in_array('Faq', $this->getVariable('selected_modules'))) {
            $extras['faq_block'] = $this->insertExtra('Faq', ModuleExtraType::block(), 'Faq');
        }
        if (in_array('Mailmotor', $this->getVariable('selected_modules'))) {
            $extras['mailmotor_subscribe'] = $this->insertExtra(
                'Mailmotor',
                ModuleExtraType::block(),
                'SubscribeForm',
                'Subscribe'
            );
            $extras['mailmotor_unsubscribe'] = $this->insertExtra(
                'Mailmotor',
                ModuleExtraType::block(),
                'UnsubscribeForm',
                'Unsubscribe'
            );
        }
        $extras['tags_block'] = $this->insertExtra('Tags', ModuleExtraType::block(), 'Tags');
        if (in_array('Profiles', $this->getVariable('selected_modules'))) {
            $extras['profiles_forgot_password'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::block(),
                'ForgotPassword',
                'ForgotPassword'
            );
            $extras['profiles_block'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::block(),
                'Dashboard'
            );
            $extras['profiles_login'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::block(),
                'Login',
                'Login'
            );
            $extras['profiles_logout'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::block(),
                'Logout',
                'Logout'
            );
            $extras['profiles_change_email'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::block(),
                'ChangeEmail',
                'ChangeEmail'
            );
            $extras['profiles_change_password'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::block(),
                'ChangePassword',
                'ChangePassword'
            );
            $extras['profiles_settings'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::block(),
                'Settings',
                'Settings'
            );
            $extras['profiles_register'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::block(),
                'Register',
                'Register'
            );
            $extras['profiles_resend_activation'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::block(),
                'ResendActivation',
                'ResendActivation'
            );
            $extras['profiles_login_box'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::widget(),
                'LoginBox',
                'LoginBox'
            );
            $extras['profiles_login_link'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::widget(),
                'LoginLink',
                'LoginLink'
            );
            $extras['profiles_secure_page'] = $this->insertExtra(
                'Profiles',
                ModuleExtraType::widget(),
                'SecurePage',
                'SecurePage'
            );
        }

        // loop languages
        foreach ($this->getLanguages() as $language) {
            // insert modules page
            $modulesPageId = $this->insertPage(
                [
                    'id' => 4,
                    'title' => SpoonFilter::ucfirst(
                        $this->getLocale('Modules', 'Core', $language, 'lbl', 'Frontend')
                    ),
                    'type' => 'page',
                    'language' => $language,
                    'parent_id' => BackendModel::HOME_PAGE_ID,
                ],
                null,
                ['extra_id' => $this->getExtraId('subpages')],
                ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
            );

            // check if pages already exist for this language
            if (!$this->hasPage($language)) {
                // re-insert homepage
                $this->insertPage(
                    [
                        'id' => BackendModel::HOME_PAGE_ID,
                        'parent_id' => BackendPagesModel::NO_PARENT_PAGE_ID,
                        'template_id' => $this->getTemplateId('home'),
                        'title' => SpoonFilter::ucfirst($this->getLocale('Home', 'Core', $language)),
                        'language' => $language,
                        'allow_move' => false,
                        'allow_delete' => false,
                    ],
                    null,
                    ['html' => __DIR__ . '/Data/' . $language . '/sample1.txt'],
                    ['extra_id' => $extras['blog_widget_recent_articles_list'], 'position' => 'main'],
                    ['extra_id' => $extras['blog_widget_recent_comments'], 'position' => 'main'],
                    ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                );

                // blog
                $this->insertPage(
                    [
                        'title' => SpoonFilter::ucfirst(
                            $this->getLocale('Blog', 'Core', $language, 'lbl', 'Frontend')
                        ),
                        'language' => $language,
                        'parent_id' => $modulesPageId,
                    ],
                    null,
                    ['extra_id' => $extras['blog_block']],
                    ['extra_id' => $extras['blog_widget_recent_comments'], 'position' => 'main'],
                    ['extra_id' => $extras['blog_widget_categories'], 'position' => 'main'],
                    ['extra_id' => $extras['blog_widget_archive'], 'position' => 'main'],
                    ['extra_id' => $extras['blog_widget_recent_articles_list'], 'position' => 'main'],
                    ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                );

                // faq
                if (in_array('Faq', $this->getVariable('selected_modules'))) {
                    $this->insertPage(
                        [
                            'title' => 'FAQ',
                            'language' => $language,
                            'parent_id' => $modulesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['faq_block']]
                    );
                }

                // mailmotor
                if (in_array('Mailmotor', $this->getVariable('selected_modules'))) {
                    $newslettersPageId = $this->insertPage(
                        [
                            'title' => 'Newsletters',
                            'language' => $language,
                            'parent_id' => $modulesPageId,
                        ]
                    );
                    $this->insertPage(
                        ['parent_id' => $newslettersPageId, 'title' => 'Subscribe', 'language' => $language],
                        null,
                        ['extra_id' => $extras['mailmotor_subscribe'], 'position' => 'main']
                    );
                    $this->insertPage(
                        ['parent_id' => $newslettersPageId, 'title' => 'Unsubscribe', 'language' => $language],
                        null,
                        ['extra_id' => $extras['mailmotor_unsubscribe'], 'position' => 'main']
                    );
                }

                // tags
                $this->insertPage(
                    [
                        'title' => 'Tags',
                        'language' => $language,
                        'parent_id' => $modulesPageId,
                    ],
                    null,
                    ['extra_id' => $extras['tags_block'], 'position' => 'main'],
                    ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                );

                // profiles
                if (in_array('Profiles', $this->getVariable('selected_modules'))) {
                    $profilesPageId = $this->insertPage(
                        [
                            'title' => 'Profiles',
                            'language' => $language,
                            'parent_id' => $modulesPageId,
                        ],
                        null,
                        ['extra_id' => $this->getExtraId('subpages')],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                    $this->insertPage(
                        [
                            'title' => SpoonFilter::ucfirst($this->getLocale('ForgotPassword', 'Core', $language, 'lbl', 'Backend')),
                            'language' => $language,
                            'parent_id' => $profilesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['profiles_forgot_password'], 'position' => 'main'],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                    $this->insertPage(
                        [
                            'title' => SpoonFilter::ucfirst(
                                $this->getLocale('ResendActivation', 'Core', $language, 'lbl', 'Backend')
                            ),
                            'language' => $language,
                            'parent_id' => $profilesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['profiles_resend_activation'], 'position' => 'main'],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                    $this->insertPage(
                        [
                            'title' => SpoonFilter::ucfirst($this->getLocale('Login', 'Core', $language, 'lbl', 'Backend')),
                            'language' => $language,
                            'parent_id' => $profilesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['profiles_login'], 'position' => 'main'],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                    $this->insertPage(
                        [
                            'title' => SpoonFilter::ucfirst($this->getLocale('Register', 'Core', $language, 'lbl', 'Backend')),
                            'language' => $language,
                            'parent_id' => $profilesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['profiles_register'], 'position' => 'main'],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                    $this->insertPage(
                        [
                            'title' => SpoonFilter::ucfirst($this->getLocale('Logout', 'Core', $language, 'lbl', 'Backend')),
                            'language' => $language,
                            'parent_id' => $profilesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['profiles_logout'], 'position' => 'main'],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                    $this->insertPage(
                        [
                            'title' => SpoonFilter::ucfirst($this->getLocale('Profile', 'Core', $language, 'lbl', 'Backend')),
                            'language' => $language,
                            'parent_id' => $profilesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['profiles_block'], 'position' => 'main'],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                    $this->insertPage(
                        [
                            'title' => SpoonFilter::ucfirst(
                                $this->getLocale('ProfileSettings', 'Core', $language, 'lbl', 'Backend')
                            ),
                            'language' => $language,
                            'parent_id' => $profilesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['profiles_settings'], 'position' => 'main'],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                    $this->insertPage(
                        [
                            'title' => SpoonFilter::ucfirst($this->getLocale('ChangeEmail', 'Core', $language, 'lbl', 'Backend')),
                            'language' => $language,
                            'parent_id' => $profilesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['profiles_change_email'], 'position' => 'main'],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                    $this->insertPage(
                        [
                            'title' => SpoonFilter::ucfirst($this->getLocale('ChangePassword', 'Core', $language, 'lbl', 'Backend')),
                            'language' => $language,
                            'parent_id' => $profilesPageId,
                        ],
                        null,
                        ['extra_id' => $extras['profiles_change_password'], 'position' => 'main'],
                        ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
                    );
                }
            }
        }
    }

    private function configureFrontendExtras(): void
    {
        $this->extraIds['search'] = $this->insertExtra('Search', ModuleExtraType::block(), 'Search');
        $this->extraIds['search_form'] = $this->insertExtra('Search', ModuleExtraType::widget(), 'SearchForm', 'Form');
        $this->extraIds['sitemap'] = $this->insertExtra($this->getModule(), ModuleExtraType::widget(), 'Sitemap', 'Sitemap');
        $this->extraIds['subpages'] = $this->insertExtra(
            $this->getModule(),
            ModuleExtraType::widget(),
            'Subpages',
            'Subpages',
            ['template' => 'SubpagesDefault.html.twig']
        );
        $this->insertExtra($this->getModule(), ModuleExtraType::widget(), 'Navigation', 'PreviousNextNavigation');
    }

    private function configureFrontendPages(): void
    {
        // loop languages
        foreach ($this->getLanguages() as $language) {
            // check if pages already exist for this language
            if ($this->hasPage($language)) {
                continue;
            }

            // insert homepage
            $this->insertPage(
                [
                    'id' => BackendModel::HOME_PAGE_ID,
                    'parent_id' => BackendPagesModel::NO_PARENT_PAGE_ID,
                    'template_id' => $this->getTemplateId('home'),
                    'title' => SpoonFilter::ucfirst($this->getLocale('Home', 'Core', $language, 'lbl', 'Backend')),
                    'language' => $language,
                    'allow_move' => false,
                    'allow_delete' => false,
                ],
                null,
                ['html' => __DIR__ . '/Data/' . $language . '/sample1.txt'],
                ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
            );

            // insert sitemap
            $this->insertPage(
                [
                    'id' => 2,
                    'title' => SpoonFilter::ucfirst(
                        $this->getLocale('Sitemap', 'Core', $language, 'lbl', 'Frontend')
                    ),
                    'type' => 'footer',
                    'language' => $language,
                ],
                null,
                ['html' => __DIR__ . '/Data/' . $language . '/sitemap.txt'],
                ['extra_id' => $this->getExtraId('sitemap')],
                ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
            );

            // insert disclaimer
            $this->insertPage(
                [
                    'id' => 3,
                    'title' => SpoonFilter::ucfirst(
                        $this->getLocale('Disclaimer', 'Core', $language, 'lbl', 'Frontend')
                    ),
                    'type' => 'footer',
                    'language' => $language,
                ],
                ['seo_index' => 'noindex', 'seo_follow' => 'nofollow'],
                [
                    'html' => __DIR__ . '/Data/' . $language .
                        '/disclaimer.txt',
                ],
                ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
            );

            // insert 404
            $this->insertPage(
                [
                    'id' => BackendModel::ERROR_PAGE_ID,
                    'title' => '404',
                    'template_id' => $this->getTemplateId('error'),
                    'type' => 'root',
                    'language' => $language,
                    'allow_move' => false,
                    'allow_delete' => false,
                ],
                null,
                ['html' => __DIR__ . '/Data/' . $language . '/404.txt'],
                ['extra_id' => $this->getExtraId('sitemap')],
                ['extra_id' => $this->getExtraId('search_form'), 'position' => 'top']
            );
        }

        // install example data if requested
        if ($this->installExample()) {
            $this->installExampleData();
        }
    }

    private function getExtraId(string $key): int
    {
        if (!array_key_exists($key, $this->extraIds)) {
            throw new \Exception('Key not set yet, please check your installer.');
        }

        return $this->extraIds[$key];
    }

    private function hasPage(string $language): bool
    {
        // @todo: Replace with PageRepository method when it exists.
        return (bool) $this->getDatabase()->getVar(
            'SELECT 1 FROM pages WHERE language = ? AND id > ? LIMIT 1',
            [$language, BackendModel::ERROR_PAGE_ID]
        );
    }
}


text:
rm -rf output-virtualbox-iso
mkdir archive
rm archive/debian-wheezy-rvm.box
mv debian-wheezy-rvm.box archive/debian-wheezy-rvm.box
mkdir log
DATE=`date +%Y%m%d_%H%M%S`
packer build debian-wheezy.json 2>&1 | tee log/packer-$DATE.txt

vagrant package --base vagrant-debian-wheezy # Produces Vagrant box

sh vagrant.sh # Copies the Vagrant box to the Vagrant setup


text:
using DotVVM.Framework.Binding;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using DotVVM.Framework.Controls;
using DotVVM.Framework.Compilation.ControlTree.Resolved;
using DotVVM.Framework.Utils;
using System.Runtime.CompilerServices;
using System.Collections.Immutable;

namespace DotVVM.Framework.Compilation.ControlTree
{
    public class DotvvmPropertyGroup : IPropertyGroupDescriptor
    {
        public FieldInfo? DescriptorField { get; }

        public ICustomAttributeProvider AttributeProvider { get; }

        public string[] Prefixes { get; }

        public string Name { get; }

        public MarkupOptionsAttribute MarkupOptions { get; }

        public DataContextChangeAttribute[] DataContextChangeAttributes { get; }

        public DataContextStackManipulationAttribute? DataContextManipulationAttribute { get; }

        public object? DefaultValue { get; }

        public Type DeclaringType { get; }
        ITypeDescriptor IControlAttributeDescriptor.DeclaringType => new ResolvedTypeDescriptor(DeclaringType);

        public ObsoleteAttribute? ObsoleteAttribute { get; }
        public Type PropertyType { get; }
        ITypeDescriptor IControlAttributeDescriptor.PropertyType => new ResolvedTypeDescriptor(PropertyType);
        public IAttributeValueMerger? ValueMerger { get; }

        private ConcurrentDictionary<string, GroupedDotvvmProperty> generatedProperties = new();

        /// <summary> The capability which declared this property. When the property is declared by an capability, it can only be used by this capability. </summary>
        public DotvvmCapabilityProperty? OwningCapability { get; }
        IPropertyDescriptor? IControlAttributeDescriptor.OwningCapability => OwningCapability;
        /// <summary> The capabilities which use this property. </summary>
        public ImmutableArray<DotvvmCapabilityProperty> UsedInCapabilities { get; private set; } = ImmutableArray<DotvvmCapabilityProperty>.Empty;
        IEnumerable<IPropertyDescriptor> IControlAttributeDescriptor.UsedInCapabilities => UsedInCapabilities;

        internal DotvvmPropertyGroup(PrefixArray prefixes, Type valueType, Type declaringType, FieldInfo? descriptorField, ICustomAttributeProvider attributeProvider, string name, object? defaultValue, DotvvmCapabilityProperty? owningCapability = null)
        {
            this.DescriptorField = descriptorField;
            this.DeclaringType = declaringType;
            this.AttributeProvider = attributeProvider;
            this.Name = name;
            this.PropertyType = valueType;
            this.Prefixes = prefixes.Values;
            (this.MarkupOptions, this.DataContextChangeAttributes, this.DataContextManipulationAttribute, this.ObsoleteAttribute) = InitFromAttributes(attributeProvider, name);
            if (MarkupOptions.AllowValueMerging)
            {
                ValueMerger = (IAttributeValueMerger?)Activator.CreateInstance(MarkupOptions.AttributeValueMerger);
            }
            this.OwningCapability = owningCapability;
        }

        private static (MarkupOptionsAttribute, DataContextChangeAttribute[], DataContextStackManipulationAttribute?, ObsoleteAttribute?)
            InitFromAttributes(ICustomAttributeProvider attributeProvider, string name)
        {
            var markupOptions = attributeProvider.GetCustomAttribute<MarkupOptionsAttribute>(true) ?? new MarkupOptionsAttribute();
            var dataContextChange = attributeProvider.GetCustomAttributes<DataContextChangeAttribute>(true);
            var dataContextManipulation = attributeProvider.GetCustomAttribute<DataContextStackManipulationAttribute>(true);
            if (dataContextManipulation != null && dataContextChange.Any()) throw new ArgumentException(
                $"{nameof(DataContextChangeAttributes)} and {nameof(DataContextManipulationAttribute)} cannot be set both at property group '{name}'.");
            var obsoleteAttribute = attributeProvider.GetCustomAttribute<ObsoleteAttribute>();
            return (markupOptions, dataContextChange.ToArray(), dataContextManipulation, obsoleteAttribute);
        }

        internal void AddUsedInCapability(DotvvmCapabilityProperty? p)
        {
            if (p is object)
                lock(this)
                {
                    if (!UsedInCapabilities.Contains(p))
                        UsedInCapabilities = UsedInCapabilities.Add(p);
                }
        }

        IPropertyDescriptor IPropertyGroupDescriptor.GetDotvvmProperty(string name) => GetDotvvmProperty(name);
        public GroupedDotvvmProperty GetDotvvmProperty(string name)
        {
            return generatedProperties.GetOrAdd(name, n => GroupedDotvvmProperty.Create(this, name));
        }

        private static ConcurrentDictionary<(Type, string), DotvvmPropertyGroup> descriptorDictionary = new();

        public static DotvvmPropertyGroup Register<TValue, TDeclaring>(PrefixArray prefixes, string name, TValue? defaultValue = default(TValue)) =>
            Register(typeof(TDeclaring), prefixes, name, typeof(TValue), defaultValue);

        public static DotvvmPropertyGroup Register(Type declaringType, PrefixArray prefixes, string name, Type valueType, object? defaultValue)
        {
            return descriptorDictionary.GetOrAdd((declaringType, name), fullName => {
                var field = declaringType.GetField(name + "GroupDescriptor", BindingFlags.Public | BindingFlags.Static);
                if (field == null) throw new InvalidOperationException($"Could not declare property group '{fullName}' because backing field was not found.");
                return new DotvvmPropertyGroup(prefixes, valueType, declaringType, field, field as ICustomAttributeProvider, name, defaultValue);
            });
        }
        internal static DotvvmPropertyGroup Register(DotvvmPropertyGroup group)
        {
            var key = (@group.DeclaringType, @group.Name);
            if (descriptorDictionary.ContainsKey(key))
            {
                throw new InvalidOperationException($"The property group {key} is already registered!");
            }
            descriptorDictionary[key] = group;
            return group;
        }
        internal static FieldInfo FindDescriptorField(Type declaringType, string name)
        {
            var fieldName = name + "GroupDescriptor";
            var field = declaringType.GetField(fieldName, BindingFlags.Public | BindingFlags.Static);
            if (field == null) throw new InvalidOperationException($"Could not declare property group '{declaringType.Name}.{name}' because backing field {fieldName} was not found.");
            return field;
        }

        public static DotvvmPropertyGroup Register(Type declaringType, PrefixArray prefixes, string name, Type valueType, ICustomAttributeProvider attributeProvider, object? defaultValue, DotvvmCapabilityProperty? declaringCapability = null)
        {
            return descriptorDictionary.GetOrAdd((declaringType, name), fullName => {
                // the field is optional, here
                var field = declaringType.GetField(name + "GroupDescriptor", BindingFlags.Public | BindingFlags.Static);
                return new DotvvmPropertyGroup(prefixes, valueType, declaringType, field, attributeProvider, name, defaultValue, declaringCapability);
            });
        }

        public static IEnumerable<DotvvmPropertyGroup> FindAttachedPropertyCandidates(string typeName)
        {
            return descriptorDictionary.Values
                .Where(pg => pg.DeclaringType.Name == typeName);
        }

        public static IEnumerable<DotvvmPropertyGroup> AllGroups => descriptorDictionary.Values;

        public static DotvvmPropertyGroup? ResolvePropertyGroup(Type declaringType, string name)
        {
            return descriptorDictionary.TryGetValue((declaringType, name), out var group) ? group : null;
        }

        public static IPropertyDescriptor? ResolvePropertyGroup(string name, bool caseSensitive, MappingMode requiredMode = default)
        {
            var nameParts = name.Split('.');
            var groups = FindAttachedPropertyCandidates(nameParts[0])
                .SelectMany(g => g.Prefixes.Select(p => new { Group = g, Prefix = p }));

            var group = groups
                .FirstOrDefault(g =>
                    nameParts[1].StartsWith(g.Prefix, caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase) &&
                    g.Group.MarkupOptions.MappingMode.HasFlag(requiredMode));
            if (group != null)
            {
                var concreteName = nameParts[1].Substring(group.Prefix.Length);
                return group.Group.GetDotvvmProperty(concreteName);
            }

            return null;
        }

        public static IEnumerable<DotvvmPropertyGroup> GetPropertyGroups(Type controlType)
        {
            DefaultControlResolver.InitType(controlType);
            foreach (var pg in descriptorDictionary.Values)
            {
                if (pg.DeclaringType.IsAssignableFrom(controlType))
                {
                    yield return pg;
                }
            }
        }

        public static void CheckAllPropertiesAreRegistered(Type controlType)
        {
            var properties =
               (from p in controlType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                where !descriptorDictionary.ContainsKey((p.DeclaringType!, p.Name))
                where p.IsDefined(typeof(PropertyGroupAttribute))
                select p).ToArray();

            if (properties.Any())
            {
                var deprecationHelp = " DotVVM version <= 3.x did support this, but this feature was removed as it lead to many issues. Please register the property group using DotvvmPropertyGroup.Register and then use VirtualPropertyGroupDictionary<T> to access the values.";
                throw new NotSupportedException($"Control '{controlType.Name}' has property groups that are not registered: {string.Join(", ", properties.Select(p => p.Name))}." + deprecationHelp);
            }
        }

        public struct PrefixArray
        {
            public readonly string[] Values;

            public PrefixArray(string[] values)
            {
                this.Values = values;
            }

            public PrefixArray(string value)
            {
                this.Values = new[] { value };
            }

            public static implicit operator PrefixArray(string val) => new PrefixArray(val);
            public static implicit operator PrefixArray(string[] val) => new PrefixArray(val);
        }
    }
}


text:
import sys

import tornado
from tchannel import TChannel

tchannel = TChannel('echo-server', hostport='127.0.0.1:0')

def close_callback(_data):
    stdin.close()
    tornado.ioloop.IOLoop.current().stop()
    sys.exit(1)

@tchannel.json.register('/echo')
def handler(request):
    return request.body

if __name__ == '__main__':
    tchannel.listen()
    stdin = tornado.iostream.PipeIOStream(sys.stdin.fileno())
    stdin.read_until_close(callback=close_callback)
    print(tchannel.hostport)
    sys.stdout.flush()
    tornado.ioloop.IOLoop.current().start()


text:
<?php

namespace netis\rbac;

/**
 * Class DbManager tracks traversed path in the auth item tree.
 * @package netis\rbac
 */
class DbManager extends \yii\rbac\DbManager implements TraceableAuthManager
{
    use AuthManagerTrait;
}


text:
package com.spotify.heroic.metric;

import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.spotify.heroic.common.GroupSet;
import com.spotify.heroic.common.Groups;
import com.spotify.heroic.common.OptionalLimit;
import com.spotify.heroic.metadata.MetadataManager;
import com.spotify.heroic.querylogging.QueryLogger;
import com.spotify.heroic.querylogging.QueryLoggerFactory;
import com.spotify.heroic.statistics.MetricBackendReporter;
import eu.toolchain.async.AsyncFramework;
import eu.toolchain.async.AsyncFuture;
import java.util.Collections;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/*
 * Start of a test for LocalMetricManager
 */
@RunWith(MockitoJUnitRunner.class)
public class LocalMetricManagerTest {
    private LocalMetricManager manager;

    @Mock
    private AsyncFramework async;

    @Mock
    private MetadataManager metadataManager;

    @Mock
    private MetricBackendReporter reporter;

    @Mock
    private MetadataManager metadata;

    @Mock
    private MetricBackend metricBackend;

    @Mock
    private AsyncFuture<FetchData> fetchDataFuture;

    @Before
    public void setup() {
        final OptionalLimit groupLimit = OptionalLimit.empty();
        final OptionalLimit seriesLimit = OptionalLimit.empty();
        final OptionalLimit aggregationLimit = OptionalLimit.empty();
        final OptionalLimit dataLimit = OptionalLimit.empty();
        final OptionalLimit concurrentQueriesBackoff = OptionalLimit.empty();
        final int fetchParallelism = 20;
        final boolean failOnLimits = true;
        final Groups groups = Groups.of("foo");
        doReturn(groups).when(metricBackend).groups();
        final GroupSet<MetricBackend> groupSet =
            GroupSet.build(Collections.singletonList(metricBackend), Optional.empty());

        final QueryLogger queryLogger = mock(QueryLogger.class);
        final QueryLoggerFactory queryLoggerFactory = mock(QueryLoggerFactory.class);
        when(queryLoggerFactory.create(any())).thenReturn(queryLogger);

        manager = new LocalMetricManager(groupLimit, seriesLimit, aggregationLimit, dataLimit,
            concurrentQueriesBackoff, fetchParallelism, failOnLimits, async, groupSet, metadata,
            reporter, queryLoggerFactory);
    }

    @Test
    public void testUseDefaultBackend() {
        assertNotNull(manager.useDefaultGroup());
    }
}


text:
using namespace std;

inline double f(double x){ return sqrt(1 - x*x);}

double trapezoidalRule(int begin, int end, int n);
double trapezoidalArea(double upper, double lower, double height);

int main(void)
{
  cout << "S = " << trapezoidalRule(0, 1, 1000) * 4 << endl;
}

double trapezoidalRule(int begin, int end, int n)
{
  double step = (end - begin)/(double)n;
  double area = 0.0;
  for(double i = begin+step; i <= end; i+= step)
  {
    area += trapezoidalArea(f(i), f(i-step), step);
  }
  return area;
}

double trapezoidalArea(double upper, double lower, double height)
{
  return (upper + lower) * height / 2;
}


text:
This is a Gitlab runner which registers before running and automaticly unregisters the runner after a stop signal has sent to the container.

## Custom TLS certificates
Custom CA certificates can be placed in `/usr/local/share/ca-certificates/ca.crt`. If this file is available, the CA certificates will be updated automatically.

## Git config
Git is configured to include the CA path `/etc/ssl/certs/ca-certificates.crt`.

## Environment Variables
The following environment variables are available to customize the runner registration:

| Variable | Required | Default | Type | Description |
| --- | --- | --- | --- | --- |
| TOKEN | yes |  | String | Runner token |
| URL | yes |  | Url | Gitlab Url |
| NAME | yes |  | String | Unique name of the runner  |
| TAG_LIST | no |  | String (comma seperated) | List of tags |
| LOCKED | no | false | Boolean |  |
| DOCKER_IMAGE | no | docker:latest | String | Default image for jobs |
| PRIVILEGED | no | false | Boolean | On true, job containers run privileged |
| SHARE_DOCKER_SOCKET | no | false | Boolean | On true, volume /var/run/docker.sock:/var/run/docker.sock is mounted. |
| TZ | no |  | Timezone String | Set custom timzone |
| SHARE_ZONEINFO | no | true | Boolean | On true and if `TZ` is set, volume /usr/share/zoneinfo:/usr/share/zoneinfo:ro is mounted |
| ADDITIONAL_OPTIONS | no |  | String | Any available options can be inserted here. To see the list of all available options run `docker run --rm --entrypoint "/usr/bin/gitlab-runner" smueller18/gitlab-runner register --help` |

Here is an example how the variable `ADDITIONAL_OPTIONS` can be used:
```bash
docker run -e ADDITIONAL_OPTIONS="--env TEST=test" smueller18/gitlab-runner
```

## Running

When starting the image, the Gitlab runner is registerd with the given options. After the runner has registered sucessfully, the Gitlab runner run command is executed.
When a stop signal is sent to the container, the Gitlab runner stops and the runner will be unregistered so that it gets removed from Gitlab immediately.

Attention: If a Gitlab runner is not stopped regularly (e.g. force kill), the runner is not unregistered. Therefore, the runner will always be listed in the runners list and must be removed from hand.

Here is an example of a docker-compose file:

```yaml
version: '2.3'

services:
  runner:
    image: smueller18/gitlab-runner
    restart: always
    environment:
      URL: ${URL}
      TOKEN: ${TOKEN}
      NAME: unique-runner-name
      PRIVILEGED: "true"
      TZ: Europe/Berlin
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /usr/share/zoneinfo:/usr/share/zoneinfo:ro
```


text:
"""ROUGe metric implementation.

This is a modified and slightly extended verison of
https://github.com/miso-belica/sumy/blob/dev/sumy/evaluation/rouge.py.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import numpy as np

import tensorflow as tf

def _len_lcs(x, y):
  """Returns the length of the Longest Common Subsequence between two seqs.

  Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence

  Args:
    x: sequence of words
    y: sequence of words

  Returns
    integer: Length of LCS between x and y
  """
  table = _lcs(x, y)
  n, m = len(x), len(y)
  return table[n, m]

def _lcs(x, y):
  """Computes the length of the LCS between two seqs.

  The implementation below uses a DP programming algorithm and runs
  in O(nm) time where n = len(x) and m = len(y).
  Source: http://www.algorithmist.com/index.php/Longest_Common_Subsequence

  Args:
    x: collection of words
    y: collection of words

  Returns:
    Table of dictionary of coord and len lcs
  """
  n, m = len(x), len(y)
  table = dict()
  for i in range(n + 1):
    for j in range(m + 1):
      if i == 0 or j == 0:
        table[i, j] = 0
      elif x[i - 1] == y[j - 1]:
        table[i, j] = table[i - 1, j - 1] + 1
      else:
        table[i, j] = max(table[i - 1, j], table[i, j - 1])
  return table

def _f_lcs(llcs, m, n):
  """Computes the LCS-based F-measure score.

  Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/
  rouge-working-note-v1.3.1.pdf

  Args:
    llcs: Length of LCS
    m: number of words in reference summary
    n: number of words in candidate summary

  Returns:
    Float. LCS-based F-measure score
  """
  r_lcs = llcs / m
  p_lcs = llcs / n
  beta = p_lcs / (r_lcs + 1e-12)
  num = (1 + (beta**2)) * r_lcs * p_lcs
  denom = r_lcs + ((beta**2) * p_lcs)
  f_lcs = num / (denom + 1e-12)
  return f_lcs

def rouge_l_sentence_level(eval_sentences, ref_sentences):
  """Computes ROUGE-L (sentence level) of two collections of sentences.

  Source: http://research.microsoft.com/en-us/um/people/cyl/download/papers/
  rouge-working-note-v1.3.1.pdf

  Calculated according to:
  R_lcs = LCS(X,Y)/m
  P_lcs = LCS(X,Y)/n
  F_lcs = ((1 + beta^2)*R_lcs*P_lcs) / (R_lcs + (beta^2) * P_lcs)

  where:
  X = reference summary
  Y = Candidate summary
  m = length of reference summary
  n = length of candidate summary

  Args:
    eval_sentences: The sentences that have been picked by the summarizer
    ref_sentences: The sentences from the referene set

  Returns:
    A float: F_lcs
  """

  f1_scores = []
  for eval_sentence, ref_sentence in zip(eval_sentences, ref_sentences):
    m = len(ref_sentence)
    n = len(eval_sentence)
    lcs = _len_lcs(eval_sentence, ref_sentence)
    f1_scores.append(_f_lcs(lcs, m, n))
  return np.mean(f1_scores, dtype=np.float32)

def rouge_l_fscore(predictions, labels, **unused_kwargs):
  """ROUGE scores computation between labels and predictions.

  This is an approximate ROUGE scoring method since we do not glue word pieces
  or decode the ids and tokenize the output.

  Args:
    predictions: tensor, model predicitons
    labels: tensor, gold output.

  Returns:
    rouge_l_fscore: approx rouge-l f1 score.
  """
  outputs = tf.to_int32(tf.argmax(predictions, axis=-1))
  # Convert the outputs and labels to a [batch_size, input_length] tensor.
  outputs = tf.squeeze(outputs, axis=[-1, -2])
  labels = tf.squeeze(labels, axis=[-1, -2])
  rouge_l_f_score = tf.py_func(rouge_l_sentence_level, (outputs, labels),
                               tf.float32)
  return rouge_l_f_score, tf.constant(1.0)

def _get_ngrams(n, text):
  """Calcualtes n-grams.

  Args:
    n: which n-grams to calculate
    text: An array of tokens

  Returns:
    A set of n-grams
  """
  ngram_set = set()
  text_length = len(text)
  max_index_ngram_start = text_length - n
  for i in range(max_index_ngram_start + 1):
    ngram_set.add(tuple(text[i:i + n]))
  return ngram_set

def rouge_n(eval_sentences, ref_sentences, n=2):
  """Computes ROUGE-N f1 score of two text collections of sentences.

  Sourece: http://research.microsoft.com/en-us/um/people/cyl/download/
  papers/rouge-working-note-v1.3.1.pdf

  Args:
    eval_sentences: The sentences that have been picked by the summarizer
    ref_sentences: The sentences from the reference set
    n: Size of ngram.  Defaults to 2.

  Returns:
    f1 score for ROUGE-N
  """

  f1_scores = []
  for eval_sentence, ref_sentence in zip(eval_sentences, ref_sentences):
    eval_ngrams = _get_ngrams(n, eval_sentence)
    ref_ngrams = _get_ngrams(n, ref_sentence)
    ref_count = len(ref_ngrams)
    eval_count = len(eval_ngrams)

    # Gets the overlapping ngrams between evaluated and reference
    overlapping_ngrams = eval_ngrams.intersection(ref_ngrams)
    overlapping_count = len(overlapping_ngrams)

    # Handle edge case. This isn't mathematically correct, but it's good enough
    if eval_count == 0:
      precision = 0.0
    else:
      precision = overlapping_count / eval_count

    if ref_count == 0:
      recall = 0.0
    else:
      recall = overlapping_count / ref_count

    f1_scores.append(2.0 * ((precision * recall) / (precision + recall + 1e-8)))

  # return overlapping_count / reference_count
  return np.mean(f1_scores, dtype=np.float32)

def rouge_2_fscore(predictions, labels, **unused_kwargs):
  """ROUGE-2 F1 score computation between labels and predictions.

  This is an approximate ROUGE scoring method since we do not glue word pieces
  or decode the ids and tokenize the output.

  Args:
    predictions: tensor, model predicitons
    labels: tensor, gold output.

  Returns:
    rouge2_fscore: approx rouge-2 f1 score.
  """

  outputs = tf.to_int32(tf.argmax(predictions, axis=-1))
  # Convert the outputs and labels to a [batch_size, input_length] tensor.
  outputs = tf.squeeze(outputs, axis=[-1, -2])
  labels = tf.squeeze(labels, axis=[-1, -2])
  rouge_2_f_score = tf.py_func(rouge_n, (labels, outputs), tf.float32)
  return rouge_2_f_score, tf.constant(1.0)


text: CKEDITOR.plugins.setLang("widget","id",{move:"Tekan dan geser untuk memindahkan",label:"%1 widget"});


text:
package edu.mayo.mprc.utilities;

import java.io.File;
import java.io.FilenameFilter;

/**
 * Filters out everything that is NOT a hidden file.
 */
public class NotHiddenFilter implements FilenameFilter {

	public NotHiddenFilter() {
	}

	@Override
	public boolean accept(final File dir, final String name) {
		return !new File(dir, name).isHidden();
	}
}


text:
(function (pro) {
    "use strict";
    pro.module('diagnostics', pro.object({
        extend: pro.extend,
        stopwatch: pro.$class('pro.diagnostics.stopwatch', function () {
            var _sw = this;
            var milliseconds = 0;
            var id = pro.GUID.create();
            var timerLen = 10;
            var increment = 10;
            var calculate = function () {
                _sw.elapsed = pro.object({
                    milliseconds: milliseconds,
                    seconds: Math.floor(milliseconds / 1000),
                    minutes: Math.floor(Math.floor(milliseconds / 1000) / 60),
                    hours: Math.floor(Math.floor(Math.floor(milliseconds / 1000) / 60) / 60)
                });
            };
            var waitCall = function () {
                milliseconds += (increment + 1);
                setTimeout(function () {
                    if (_sw.started === true) {
                        waitCall();
                    }
                }, timerLen);
            };
            var timerCode;
            this.started = false;
            this.start = function () {
                this.started = true;
                waitCall();
                return this;
            };
            this.stop = function () {
                this.started = false;
                calculate();
                return this;
            };
            this.reset = function () {
                this.started = false;
                this.elapsed = null;
                milliseconds = 0;
                return this;
            };
            this.elapsed = null;
        })
    }));
})(pro);


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/html; charset=utf-8" />

    <title>pylab_examples example code: dashpointlabel.py — Matplotlib 1.3.1 documentation</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Matplotlib 1.3.1 documentation"
          href="../../_static/opensearch.xml"/>
    <link rel="top" title="Matplotlib 1.3.1 documentation" href="../../index.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <link rel="stylesheet" href="../_static/pythonista.css" type="text/css" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          modules |

Matplotlib 1.3.1 documentation »

pylab_examples example code: dashpointlabel.py¶

(Source code, png)

import matplotlib.pyplot as plt

DATA = ((1, 3),
        (2, 4),
        (3, 1),
        (4, 2))
# dash_style =
#     direction, length, (text)rotation, dashrotation, push
# (The parameters are varied to show their effects,
# not for visual appeal).
dash_style = (
    (0, 20, -15, 30, 10),
    (1, 30, 0, 15, 10),
    (0, 40, 15, 15, 10),
    (1, 20, 30, 60, 10),
    )

fig, ax = plt.subplots()

(x,y) = zip(*DATA)
ax.plot(x, y, marker='o')
for i in range(len(DATA)):
    (x,y) = DATA[i]
    (dd, dl, r, dr, dp) = dash_style[i]
    #print 'dashlen call', dl
    t = ax.text(x, y, str((x,y)), withdash=True,
               dashdirection=dd,
               dashlength=dl,
               rotation=r,
               dashrotation=dr,
               dashpush=dp,
               )

ax.set_xlim((0.0, 5.0))
ax.set_ylim((0.0, 5.0))

plt.show()

Keywords: python, matplotlib, pylab, example, codex (see Search examples)

    © Copyright 2002 - 2012 John Hunter, Darren Dale, Eric Firing, Michael Droettboom and the matplotlib development team; 2012 - 2013 The matplotlib development team.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>MethodNotFoundException (EL 3.0 API Documentation - Apache Tomcat 9.0.0.M11)</title>
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

EL 3.0 - Apache Tomcat 9.0.0.M11

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javax.el

Class MethodNotFoundException

java.lang.Object

java.lang.Throwable

java.lang.Exception

java.lang.RuntimeException

javax.el.ELException

javax.el.MethodNotFoundException

All Implemented Interfaces:

java.io.Serializable

public class MethodNotFoundException
extends ELException

See Also:

Serialized Form

Constructor Summary

Constructors

Constructor and Description

MethodNotFoundException()

MethodNotFoundException(java.lang.String message)

MethodNotFoundException(java.lang.String message,
                       java.lang.Throwable cause)

MethodNotFoundException(java.lang.Throwable cause)

Method Summary

Methods inherited from class java.lang.Throwable

addSuppressed, fillInStackTrace, getCause, getLocalizedMessage, getMessage, getStackTrace, getSuppressed, initCause, printStackTrace, printStackTrace, printStackTrace, setStackTrace, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

MethodNotFoundException

public MethodNotFoundException()

MethodNotFoundException

public MethodNotFoundException(java.lang.String message)

MethodNotFoundException

public MethodNotFoundException(java.lang.Throwable cause)

MethodNotFoundException

public MethodNotFoundException(java.lang.String message,
                               java.lang.Throwable cause)

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

EL 3.0 - Apache Tomcat 9.0.0.M11

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2000-2016 Apache Software Foundation. All Rights Reserved.


text:
using System.Collections.Generic;
using System.Drawing;

using ZXing;

namespace CommandLineDecoder
{
    internal sealed class Config
    {
        public IDictionary<DecodeHintType, object> Hints { get; set; }
        public bool TryHarder { get; set; }
        public bool PureBarcode { get; set; }
        public bool ProductsOnly { get; set; }
        public bool DumpResults { get; set; }
        public bool DumpBlackPoint { get; set; }
        public bool Multi { get; set; }
        public bool Brief { get; set; }
        public bool Recursive { get; set; }
        public int[] Crop { get; set; }
        public int Threads { get; set; }
        public bool AutoRotate { get; set; }
        public Bitmap BitmapFromClipboard { get; set; }

        public Config()
        {
            Threads = 1;
        }
    }
}