text:
"""\
This script prints out a list of undocumented symbols found in
Python include files, prefixed by their tag kind.

Pass Python's include files to ctags, parse the output into a
dictionary mapping symbol names to tag kinds.

Then, the .tex files from Python docs are read into a giant string.

Finally all symbols not found in the docs are written to standard
output, prefixed with their tag kind.
"""

# Which kind of tags do we need?
TAG_KINDS = "dpst"

# Doc sections to use
DOCSECTIONS = ["api"]# ["api", "ext"]

# Only print symbols starting with this prefix,
# to get all symbols, use an empty string
PREFIXES = ("Py", "PY")

INCLUDEPATTERN = "*.h"

# end of customization section

# Tested with EXUBERANT CTAGS
# see http://ctags.sourceforge.net
#
# ctags fields are separated by tabs.
# The first field is the name, the last field the type:
# d macro definitions (and #undef names)
# e enumerators
# f function definitions
# g enumeration names
# m class, struct, or union members
# n namespaces
# p function prototypes and declarations
# s structure names
# t typedefs
# u union names
# v variable definitions
# x extern and forward variable declarations

import os, glob, re, sys

def findnames(file, prefixes=()):
    names = {}
    for line in file.xreadlines():
        if line[0] == '!':
            continue
        fields = line.split()
        name, tag = fields[0], fields[-1]
        if tag == 'd' and name.endswith('_H'):
            continue
        if prefixes:
            sw = name.startswith
            for prefix in prefixes:
                if sw(prefix):
                    names[name] = tag
        else:
            names[name] = tag
    return names

def print_undoc_symbols(prefix, docdir, incdir):
    docs = []

    for sect in DOCSECTIONS:
        for file in glob.glob(os.path.join(docdir, sect, "*.tex")):
            docs.append(open(file).read())

    docs = "\n".join(docs)

    incfiles = os.path.join(incdir, INCLUDEPATTERN)

    fp = os.popen("ctags -IPyAPI_FUNC -IPy_GCC_ATTRIBUTE --c-types=%s -f - %s"
                  % (TAG_KINDS, incfiles))
    dict = findnames(fp, prefix)
    names = dict.keys()
    names.sort()
    for name in names:
        if not re.search("%s\\W" % name, docs):
            print dict[name], name

if __name__ == '__main__':
    srcdir = os.path.dirname(sys.argv[0])
    incdir = os.path.normpath(os.path.join(srcdir, "../../Include"))
    docdir = os.path.normpath(os.path.join(srcdir, ".."))

    print_undoc_symbols(PREFIXES, docdir, incdir)


text:
<?php

// These are called automatically by the Payment modules list - do not change the names
$method_list_logo              = '';
$_['text_mollie_banktransfer'] = $method_list_logo;
$_['text_mollie_belfius']      = $method_list_logo;
$_['text_mollie_bitcoin']      = $method_list_logo;
$_['text_mollie_creditcard']   = $method_list_logo;
$_['text_mollie_directdebit']  = $method_list_logo;
$_['text_mollie_ideal']        = $method_list_logo;
$_['text_mollie_kbc']          = $method_list_logo;
$_['text_mollie_mistercash']   = $method_list_logo;
$_['text_mollie_paypal']       = $method_list_logo;
$_['text_mollie_paysafecard']  = $method_list_logo;
$_['text_mollie_sofort']       = $method_list_logo;

// Heading
$_['heading_title']           = "Mollie";
$_['title_global_options']    = "Options for all Mollie modules";
$_['title_payment_status']    = "Payment statuses";
$_['title_mod_about']         = "About this module";
$_['footer_text']             = "Payment services";

// Module names
$_['name_mollie_banktransfer'] = "Bank transfer";
$_['name_mollie_belfius']      = "Belfius Direct Net";
$_['name_mollie_bitcoin']      = "Bitcoin";
$_['name_mollie_creditcard']   = "Creditcard";
$_['name_mollie_directdebit']  = "Direct debit";
$_['name_mollie_ideal']        = "iDEAL";
$_['name_mollie_kbc']          = "KBC/CBC Payment Button";
$_['name_mollie_mistercash']   = "Bancontact/MisterCash";
$_['name_mollie_paypal']       = "PayPal";
$_['name_mollie_paysafecard']  = "paysafecard";
$_['name_mollie_sofort']       = "SOFORT Banking";

// Text
$_['text_edit']                    = "Edit";
$_['text_payment']                 = "Payment";
$_['text_success']                 = "Success: You have successfully modified your Mollie settings!";
$_['text_missing_api_key']         = "Please fill out your API key below.";
$_['text_activate_payment_method'] = 'Enable this payment method in your Mollie dashboard.';
$_['text_no_status_id']            = "- Do not update the order status (not recommended) -";

// Entry
$_['entry_payment_method']           = "Payment method";
$_['entry_activate']                 = "Activate";
$_['entry_sort_order']               = "Sort order";
$_['entry_status']                   = "Status";
$_['entry_api_key']                  = "API key";
$_['entry_description']              = "Description";
$_['entry_show_icons']               = "Show icons";
$_['entry_show_order_canceled_page'] = "Show message if payment is cancelled";

// Help
$_['help_view_profile']             = 'You can find your API key in your Mollie website profiles.';
$_['help_status']                   = "Activate the module";
$_['help_api_key']                  = 'Enter the api_key of the website profile you want to use. The API key starts with test_ or live_.';
$_['help_description']              = 'This description will appear on the bank / card statement of your customer. You may use a maximum of 29 characters. TIP: Use %, this will be replaced by the order id of the payment. Don\'t forget % can be multiple characters long!';
$_['help_show_icons']               = 'Show icons next to the Mollie payment methods on the checkout page.';
$_['help_show_order_canceled_page'] = 'Show a message to the customer if a payment is cancelled, before redirecting the customer back to their shopping cart.';

// Info
$_['entry_module']            = "Module";
$_['entry_mod_status']        = "Module status";
$_['entry_comm_status']       = "Communication status";
$_['entry_support']           = "Support";

$_['entry_version']           = 'Mollie Opencart';

// Error
$_['error_permission']        = "Warning: You don't have permission to modify the Mollie payment methods.";
$_['error_api_key']           = "Mollie API key is required!";
$_['error_api_key_invalid']   = "Invalid API key!";
$_['error_description']       = "Description is required!";
$_['error_file_missing']      = "File does not exist";

// Status
$_['entry_pending_status']    = "Payment created status";
$_['entry_failed_status']     = "Payment failed status";
$_['entry_canceled_status']   = "Payment canceled status";
$_['entry_expired_status']    = "Payment expired status";
$_['entry_processing_status'] = "Payment successful status";

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="reassign">
        <note>
            Frames file for 'reassign' based on sentences in financial subcorpus.
            Verbnet entry 13.3, other framed members include allocate, award,
            concede, grant, promise and vote.  Comparison to those.  No Framenet
            entry.
        </note>

        <roleset id="reassign.01" name="give, associate with again" vncls="13.3">
            <roles>
                <role descr="agent, assigner" n="0">

                    <vnrole vncls="13.3" vntheta="Agent"/>
                </role>

                <role descr="thing assigned" n="1">

                    <vnrole vncls="13.3" vntheta="Theme"/>
                </role>

                <role descr="assigned to" n="2">

                    <vnrole vncls="13.3" vntheta="Recipient"/>
                </role>

            </roles>

            <example name="just transitive">
                <inflection aspect="perfect" form="participle" person="third" tense="present" voice="active"/>
                <text>
                    Fluor Daniel already has reassigned most of its work crew, the
                    sources said.
                </text>
                <arg n="0">Fluor Daniel</arg>
                <arg f="TMP" n="M">already</arg>
                <rel>reassigned</rel>
                <arg n="1">most of its work crew</arg>
            </example>

            <note>
                Reassign seems to not take Arg2 most of the time, while assign does.
                How odd.
            </note>

        </roleset>
    </predicate>
</frameset>


text:
package com.hyurumi.fb_bot_boilerplate.models.send;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import com.hyurumi.fb_bot_boilerplate.Main;
import com.hyurumi.fb_bot_boilerplate.models.common.Recipient;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.io.IOException;

import static com.hyurumi.fb_bot_boilerplate.Main.sAccessToken;
import java.util.Arrays;
import java.util.List;

/**
 * Created by genki.furumi on 4/15/16.
 */
public class Message {

    private transient final OkHttpClient HTTP_CLIENT;
    private transient final Gson GSON;

    {
        HTTP_CLIENT = new OkHttpClient();
        GSON = new Gson();
    }

    final private Attachment attachment;
    final private String text;

    // add by kyawswar
    @SerializedName("quick_replies")
    final private List<QuickReply> quickReplies;

    private Message(Attachment attachment, String text) {
        this.attachment = attachment;
        this.text = text;
        this.quickReplies = null;
    }

    private Message(String text, QuickReply... quickReplies) {
        this.attachment = null;
        this.text = text;
        this.quickReplies = Arrays.asList(quickReplies);
    }

    public static Message Text(String text) {
        return new Message(null, text);
    }

    public static Message QuickReply(String text, QuickReply... quickReplies) {
        return new Message(text, quickReplies);
    }

    public static Message Image(String url) {
        return new Message(Attachment.Image(url), null);
    }

    public static Message Button(String text) {
        return new Message(Attachment.Template(Payload.Button(text)), null);
    }

    public static Message Generic() {
        return new Message(Attachment.Template(Payload.Generic()), null);
    }

    public boolean addQuickReply(QuickReply reply) {
        return quickReplies.add(reply);
    }

    public boolean addElement(Element element) {
        return attachment.addElement(element);
    }

    public boolean addButton(Button button) {
        return attachment.addButton(button);
    }

    public Response sendTo(String recipientId) throws IOException {

        RequestBody body = RequestBody.create(Main.JSON, GSON.toJson(new MessageWrapper(recipientId, this)));
        Request request = new Request.Builder()
                .url(Main.END_POINT + "?access_token=" + sAccessToken)
                .header("Content-Type", "application/json; charset=UTF-8")
                .post(body)
                .build();
        okhttp3.Response response = HTTP_CLIENT.newCall(request).execute();
        final int code = response.code();
        Response returnValue = null;
        if (code == 200) {
            System.out.println("WORK!");
            returnValue = GSON.fromJson(response.body().string(), Response.class);
        }else {
            System.out.println("ERROR: " + response.body().string());
        }
        response.body().close();
        return returnValue;
    }

    class MessageWrapper {
        private final Recipient recipient;
        private final Message message;
        MessageWrapper(String recipientId, Message message) {
            this.recipient = new Recipient(recipientId);
            this.message = message;
        }
    }
}


text:
<bill session="110" type="hr" number="503" updated="2009-01-09T08:54:54-05:00">
	<status><introduced date="1182312000" datetime="2007-06-20"/></status>

	<introduced date="1182312000" datetime="2007-06-20"/>
	<titles>
		<title type="official" as="introduced">Commending the Middle East Investment Initiative.</title>
	</titles>
	<sponsor id="400011"/>
	<cosponsors>
		<cosponsor id="400370" joined="2007-06-20"/>
		<cosponsor id="400013" joined="2007-07-25"/>
		<cosponsor id="400415" joined="2007-07-10"/>
	</cosponsors>
	<actions>
		<action date="1182312000" datetime="2007-06-20"><text>Referred to the House Committee on Foreign Affairs.</text></action>
	</actions>
	<committees>

	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>
	6/20/2007--Introduced.<br/>Commends the Middle East Investment Initiative (MEII) and its contributors for their vision and initiative. Expresses the House of Representatives' belief that improved economic activity can help bring about regional stability and peace. Encourages the participation and contributions of individuals, institutions, and foreign governments in supporting the MEII. Pledges support for the MEII and other efforts to stimulate the economy of the Palestinian people.
	</summary>
</bill>


text:
package alotoc.graphics.view;

import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.io.FileInputStream;
import java.io.ObjectInputStream;

import alotoc.Constants;
import alotoc.logic.AlotocRunnables;
import alotoc.logic.ClockMouseListener;

/**
 * This is a Frame for the main of the program. It contains the actual clock
 * view.
 *
 * @author Kazeheki
 * @see AbstractAlotocFrame
 */
@SuppressWarnings("serial")
public class MainFrame extends AbstractAlotocFrame {

	/** The clockView of this frame. */
	private final ClockView cv;

	/** This Frame. */
	private static MainFrame instance = null;

	/**
	 * Get an instance of the MainFrame.
	 * @return Instance of MainFrame.
	 */
	public static MainFrame getInstance(){
		if(instance == null){
			instance = new MainFrame();
		}
		return instance;
	}

	/**
	 * Ctor.
	 */
	private MainFrame() {
		super(MouseInfo.getPointerInfo().getLocation(), Constants.MAIN_FRM_WIDTH, Constants.MAIN_FRM_HEIGHT, "Clock");
		if(fileIsExistent()){
			int[] xY = loadPosition();
			this.setLocation(xY[0], xY[1]);
		}
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setBackground(new Color(0, 0, 0, 0));
		this.addMouseListener(new ClockMouseListener(this));
		cv = new ClockView(this);
		this.add(cv);

		Thread t = new Thread(AlotocRunnables.clockTickRunnable(this));
		t.setName("CLOCK");
		t.start();

		this.setVisible(true);
	}

	/**
	 * Get the ClockView of this Frame.
	 *
	 * @return The ClockView of this Frame.
	 */
	public final ClockView getClockView(){
		return cv;
	}

	/**
	 * Get the position saved in the storage file.
	 * Returns array of size 2.
	 * array[0] - x-Coordinate,
	 * array[1] - y-Coordinate;
	 * @return Coordinates of last position.
	 */
	private final int[] loadPosition(){
		int[] arr = new int[2];

		try{
			FileInputStream fileStream = new FileInputStream(file);
			ObjectInputStream objStream = new ObjectInputStream(fileStream);

			arr = (int[]) objStream.readObject();

			objStream.close();
			fileStream.close();
		}catch(Exception e){
			Point p = MouseInfo.getPointerInfo().getLocation();
			arr[0] = p.x;
			arr[1] = p.y;
		}

		return arr;
	}
}


text:
@interface SLAnim () {
    UIView *_view;
    NSArray *_times;

    NSMutableArray *_properties;

    float _delay;
    UIViewAnimationOptions _animationOption;
    id _callbackTarget;
    SEL _callbackSelector;
    id _callbackObject;

    int _currentAnimationStep;
    BOOL _isAnimating;
}
@end

@implementation SLAnim

#pragma mark - Init

- (id) init {
    return [self initWithView:nil];
}

- (id) initWithView:(UIView *)view {
    return [self initWithView:view times:nil];
}
- (id) initWithView:(UIView *)view times:(NSArray *)times {
    self = [super init];
    _view = view;
    _isAnimating = NO;
    _properties = [NSMutableArray new];
    _delay = 0;
    _animationOption = UIViewAnimationOptionCurveLinear;
    _times = times;
    for (int index = 0; index < SLA_PROP_COUNT; index++)
        [_properties addObject:[NSNull null]];
    return self;
}

#pragma mark - Property settings

- (void) setView:(UIView *)view {
    _view = view;
}
- (void)setTimes:(NSArray *)times {
    _times = times;
}

- (void)setProp:(NSUInteger)prop values:(NSArray *)values {
    switch (prop) {
        case SLA_PROP_ALPHA:
            [_properties replaceObjectAtIndex:SLA_PROP_ALPHA withObject: values];
            break;

        case SLA_PROP_CENTER:
            [_properties replaceObjectAtIndex:SLA_PROP_CENTER withObject:values];
            break;

        case SLA_PROP_COLOR_BG:
            [_properties replaceObjectAtIndex:SLA_PROP_COLOR_BG withObject:values];
            break;

        case SLA_PROP_FRAME:
            [_properties replaceObjectAtIndex:SLA_PROP_FRAME withObject:values];
            break;

        case SLA_PROP_SHADOW_OPACITY:
            [_properties replaceObjectAtIndex:SLA_PROP_SHADOW_OPACITY withObject:values];
            break;

        case SLA_PROP_TRANSFORM_XY:
            [_properties replaceObjectAtIndex:SLA_PROP_TRANSFORM_XY withObject:values];
            break;

        case SLA_PROP_TRANSFORM_X:
            [_properties replaceObjectAtIndex:SLA_PROP_TRANSFORM_X withObject:values];
            break;

        case SLA_PROP_TRANSFORM_Y:
            [_properties replaceObjectAtIndex:SLA_PROP_TRANSFORM_Y withObject:values];
            break;

        case SLA_PROP_ROTATE:
            [_properties replaceObjectAtIndex:SLA_PROP_ROTATE withObject:values];
            break;

        default:
            break;
    }
}
- (void) setDelay:(float)aDelay {
    _delay = aDelay;
}
- (void) setAnimationOption:(NSUInteger)option {
    switch (option) {
        case SLA_TIME_LINEAR:
            _animationOption = UIViewAnimationOptionCurveLinear;
            break;
        case SLA_TIME_EASE_IN:
            _animationOption = UIViewAnimationOptionCurveEaseIn;
            break;
        case SLA_TIME_EASE_OUT:
            _animationOption = UIViewAnimationOptionCurveEaseOut;
            break;
        case SLA_TIME_EASE_IN_OUT:
            _animationOption = UIViewAnimationOptionCurveEaseInOut;
            break;
        default:
            break;
    }
}
- (void) setCallbackTarget:(id)callbackTarget callbackSelector:(SEL)callbackSelector {
    [self setCallbackTarget:callbackTarget callbackSelector:callbackSelector callbackObject:nil];
}
- (void) setCallbackTarget:(id)callbackTarget callbackSelector:(SEL)callbackSelector callbackObject:(id)callbackObject {
    _callbackTarget = callbackTarget;
    _callbackSelector = callbackSelector;
    _callbackObject = callbackObject;
}

#pragma mark - Animation

- (BOOL) animate {

    if (![self canAnimate])
        return NO;

    _isAnimating = YES;
    _currentAnimationStep = 0;
    [self animateViewWithPropsAtStep:_currentAnimationStep];

    if (_delay == 0) {
        [self animationStep];
    } else {
        [self performSelector:@selector(animationStep) withObject:nil afterDelay:_delay];
    }

    return YES;
}

- (void) animationStep {
    [UIView animateWithDuration:[[_times objectAtIndex:_currentAnimationStep] doubleValue] delay:0
                        options:(_animationOption | UIViewAnimationOptionAllowUserInteraction)
                     animations:^{
                         [self animateViewWithPropsAtStep:self->_currentAnimationStep + 1];
                     } completion: ^(BOOL finished) {
                         self->_currentAnimationStep++;

                         if (self->_currentAnimationStep < [self->_times count]) {
                             [self animationStep];

                         } else {
                             [self completionCallBack];
                         }
                     }];
}

- (void) animateViewWithPropsAtStep:(int)step {
    for (int index = 0; index < [_properties count]; index++)
        if (![[_properties objectAtIndex:index] isEqual:[NSNull null]])
            [self setViewWithProps:index step:step];
}

- (void) setViewWithProps:(int)property step:(int)step {
    if (property == SLA_PROP_ALPHA)
        [_view setAlpha:[[[_properties objectAtIndex:property] objectAtIndex:step] doubleValue]];

    if (property == SLA_PROP_COLOR_BG)
        [_view setBackgroundColor:[[_properties objectAtIndex:property] objectAtIndex:step]];

    if (property == SLA_PROP_CENTER)
        [_view setCenter:[[[_properties objectAtIndex:property] objectAtIndex:step] CGPointValue]];

    if (property == SLA_PROP_FRAME)
        [_view setFrame:[[[_properties objectAtIndex:property] objectAtIndex:step] CGRectValue]];

    if (property == SLA_PROP_SHADOW_OPACITY && step != 0)
        [self setViewShadowOpacityFrom:[[_properties objectAtIndex:property] objectAtIndex:step-1]
                                    to:[[_properties objectAtIndex:property] objectAtIndex:step]
                              duration:[[_times objectAtIndex:step-1] floatValue]];

    if (property == SLA_PROP_TRANSFORM_XY) {
        [_view setTransform:CGAffineTransformIdentity];
        [_view setTransform:CGAffineTransformMakeScale([[[_properties objectAtIndex:property] objectAtIndex:step] doubleValue]+0.0001,      // iOS Glitch
                                                       [[[_properties objectAtIndex:property] objectAtIndex:step] doubleValue]+0.0001)];    // Exactly 0 be cannot animated
    }

    if (property == SLA_PROP_TRANSFORM_Y) {
        [_view setTransform:CGAffineTransformIdentity];
        [_view setTransform:CGAffineTransformMakeScale(1, [[[_properties objectAtIndex:property] objectAtIndex:step] doubleValue]+0.0001)];
    }
    if (property == SLA_PROP_TRANSFORM_X) {
        [_view setTransform:CGAffineTransformIdentity];
        [_view setTransform:CGAffineTransformMakeScale([[[_properties objectAtIndex:property] objectAtIndex:step] doubleValue]+0.0001, 1)];
    }

    if (property == SLA_PROP_ROTATE && step != 0) {
        [self setViewRotation:[[_properties objectAtIndex:property] objectAtIndex:step] duration:[[_times objectAtIndex:step-1] floatValue]];
    }

}

- (void) setViewShadowOpacityFrom:(NSValue *)from to:(NSValue *)to duration:(float)duration {
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"shadowOpacity"];
    anim.fromValue = from;
    anim.toValue = to;
    anim.duration = duration;
    [_view.layer addAnimation:anim forKey:@"shadowOpacity"];
}
- (void) setViewRotation:(NSValue *)value duration:(float)duration {
    CALayer *currentLayer = (CALayer *)[_view.layer presentationLayer];
    NSValue *from = (NSNumber *)[currentLayer valueForKeyPath:@"transform.rotation.z"];

    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    anim.fromValue = from;
    anim.toValue = value;
    anim.duration = duration;
    anim.fillMode = kCAFillModeForwards;
    anim.removedOnCompletion = NO;
    anim.timingFunction = [self viewAnimationCurveToCoreAnimationTiming:_animationOption];
    [_view.layer addAnimation:anim forKey:@"rotation"];
}

- (BOOL) canAnimate {
    if (_isAnimating) {
        [self log:@"%@ Already animating"];
        return NO;
    }

    if (!_view) {
        [self log:@"%@ View must be set", LOG_D];
        return NO;
    }
    if (!_times || [_times count] == 0) {
        [self log:@"%@ Animation times must be set", LOG_D];
        return NO;
    }

    if (_delay < 0) {
        [self log:@"%@ Cannot have negative delay", LOG_D];
        return NO;
    }

    // Every other property must have 1 more argument than time
    BOOL hasProp = NO;
    for (int index = 0; index < [_properties count]; index++) {
        if (![[_properties objectAtIndex:index] isEqual:[NSNull null]]) {
            hasProp = YES;
            if ([[_properties objectAtIndex:index] count] != [_times count] + 1) {
                [self log:@"%@ Invalid number of %@(s). Have [%d], needs [%d]", LOG_D, [self nameForProp:index], [[_properties objectAtIndex:index] count], [_times count]+1];
                return NO;
            }
        }
    }

    if (hasProp == NO) {
        [self log:@"%@ Must have at least one animatable property", LOG_D];
        return NO;
    }

    // Cannot have properties that clash

    if (![[_properties objectAtIndex:SLA_PROP_CENTER] isEqual:[NSNull null]] &&
        ![[_properties objectAtIndex:SLA_PROP_FRAME] isEqual:[NSNull null]]) {
        [self log:@"%@ Cannot animate both center and frame at the same time", LOG_D];
        return NO;
    } else if (![[_properties objectAtIndex:SLA_PROP_TRANSFORM_XY] isEqual:[NSNull null]] &&
                   ![[_properties objectAtIndex:SLA_PROP_TRANSFORM_X] isEqual:[NSNull null]]) {
        [self log:@"%@ Cannot animate both scale (x && y) and scale (y) scale at the same time", LOG_D];
        return NO;
    }

    return YES;
}

#pragma mark - Variable arguments to Arrays

- (NSMutableArray *)getArrayFloats:(NSNumber *)firstArg args:(va_list)args {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSNumber *arg = firstArg; arg != nil; arg = va_arg(args, NSNumber *))
        [array addObject:arg];
    va_end(args);
    return array;
}
- (NSMutableArray *)getArrayColors:(UIColor *)firstArg args:(va_list)args {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (UIColor *arg = firstArg; arg != nil; arg = va_arg(args, UIColor *))
        [array addObject:arg];
    va_end(args);
    return array;
}
- (NSMutableArray *)getArrayValues:(NSValue *)firstArg args:(va_list)args {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSValue *arg = firstArg; arg != nil; arg = va_arg(args, NSValue *))
        [array addObject:arg];
    va_end(args);
    return array;
}

#pragma mark - Callback

- (void) completionCallBack {
    [self invokeCallbackOnTarget:_callbackTarget callbackSelector:_callbackSelector callbackObject:_callbackObject];
}

- (void) invokeCallbackOnTarget:(id)target callbackSelector:(SEL)sel callbackObject:(id)obj {
    if (!target || !sel)
        return;

    IMP imp = [target methodForSelector:sel];
    if (!obj) {
        void (*func)(id, SEL) = (void *)imp;
        func(target, sel);
    } else {
        void (*func)(id, SEL, id) = (void *)imp;
        func(target, sel, obj);
    }

    return;
}

#pragma mark - Helper / Printers

- (NSString *) nameForProp:(int)prop {
    if (prop == SLA_PROP_ALPHA) return @"Alpha";
    if (prop == SLA_PROP_COLOR_BG) return @"Background Colors";
    if (prop == SLA_PROP_CENTER) return @"Centers";
    if (prop == SLA_PROP_FRAME) return @"Frames";
    if (prop == SLA_PROP_SHADOW_OPACITY) return @"ShadowOpacities";
    if (prop == SLA_PROP_TRANSFORM_XY) return @"Transforms(scale)";
    if (prop == SLA_PROP_TRANSFORM_X) return @"Transforms(horizontal scale)";
    if (prop == SLA_PROP_TRANSFORM_Y) return @"Transforms(vertical scale)";
    return @"Unknown";
}

- (void)log:(NSString *)format, ... {
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"HH:mm:ss.SSS"];
    printf("[%s] ", [[formatter stringFromDate:[NSDate new]] UTF8String]);
    va_list args;
    va_start(args, format);
    fputs([[[NSString alloc] initWithFormat:format arguments:args] UTF8String], stdout);
    va_end(args);
    printf("\n");
}
- (CAMediaTimingFunction *) viewAnimationCurveToCoreAnimationTiming:(UIViewAnimationOptions)curve {
    NSString *caMediaTiming = kCAMediaTimingFunctionLinear;
    if (curve == UIViewAnimationOptionCurveEaseIn) caMediaTiming = kCAMediaTimingFunctionEaseIn;
    if (curve == UIViewAnimationOptionCurveEaseOut) caMediaTiming = kCAMediaTimingFunctionEaseOut;
    if (curve == UIViewAnimationOptionCurveEaseInOut) caMediaTiming = kCAMediaTimingFunctionEaseInEaseOut;
    return [CAMediaTimingFunction functionWithName:caMediaTiming];
}

@end


text:
"""Dependency finders for the Qt framework."""

import abc
import re
import os
import typing as T

from . import (
    ExtraFrameworkDependency, DependencyException, DependencyMethods,
    PkgConfigDependency,
)
from .base import ConfigToolDependency, DependencyFactory
from .. import mlog
from .. import mesonlib

if T.TYPE_CHECKING:
    from ..compilers import Compiler
    from ..envconfig import MachineInfo
    from ..environment import Environment

def _qt_get_private_includes(mod_inc_dir: str, module: str, mod_version: str) -> T.List[str]:
    # usually Qt5 puts private headers in /QT_INSTALL_HEADERS/module/VERSION/module/private
    # except for at least QtWebkit and Enginio where the module version doesn't match Qt version
    # as an example with Qt 5.10.1 on linux you would get:
    # /usr/include/qt5/QtCore/5.10.1/QtCore/private/
    # /usr/include/qt5/QtWidgets/5.10.1/QtWidgets/private/
    # /usr/include/qt5/QtWebKit/5.212.0/QtWebKit/private/

    # on Qt4 when available private folder is directly in module folder
    # like /usr/include/QtCore/private/
    if int(mod_version.split('.')[0]) < 5:
        return []

    private_dir = os.path.join(mod_inc_dir, mod_version)
    # fallback, let's try to find a directory with the latest version
    if not os.path.exists(private_dir):
        dirs = [filename for filename in os.listdir(mod_inc_dir)
                if os.path.isdir(os.path.join(mod_inc_dir, filename))]

        for dirname in sorted(dirs, reverse=True):
            if len(dirname.split('.')) == 3:
                private_dir = dirname
                break
    return [private_dir, os.path.join(private_dir, 'Qt' + module)]

def get_qmake_host_bins(qvars: T.Dict[str, str]) -> str:
    # Prefer QT_HOST_BINS (qt5, correct for cross and native compiling)
    # but fall back to QT_INSTALL_BINS (qt4)
    if 'QT_HOST_BINS' in qvars:
        return qvars['QT_HOST_BINS']
    return qvars['QT_INSTALL_BINS']

def _get_modules_lib_suffix(version: str, info: 'MachineInfo', is_debug: bool) -> str:
    """Get the module suffix based on platform and debug type."""
    suffix = ''
    if info.is_windows():
        if is_debug:
            suffix += 'd'
        if version.startswith('4'):
            suffix += '4'
    if info.is_darwin():
        if is_debug:
            suffix += '_debug'
    if mesonlib.version_compare(version, '>= 5.14.0'):
        if info.is_android():
            if info.cpu_family == 'x86':
                suffix += '_x86'
            elif info.cpu_family == 'x86_64':
                suffix += '_x86_64'
            elif info.cpu_family == 'arm':
                suffix += '_armeabi-v7a'
            elif info.cpu_family == 'aarch64':
                suffix += '_arm64-v8a'
            else:
                mlog.warning(f'Android target arch "{info.cpu_family}"" for Qt5 is unknown, '
                             'module detection may not work')
    return suffix

class QtExtraFrameworkDependency(ExtraFrameworkDependency):
    def __init__(self, name: str, env: 'Environment', kwargs: T.Dict[str, T.Any], language: T.Optional[str] = None):
        super().__init__(name, env, kwargs, language=language)
        self.mod_name = name[2:]

    def get_compile_args(self, with_private_headers: bool = False, qt_version: str = "0") -> T.List[str]:
        if self.found():
            mod_inc_dir = os.path.join(self.framework_path, 'Headers')
            args = ['-I' + mod_inc_dir]
            if with_private_headers:
                args += ['-I' + dirname for dirname in _qt_get_private_includes(mod_inc_dir, self.mod_name, qt_version)]
            return args
        return []

class _QtBase:

    """Mixin class for shared componenets between PkgConfig and Qmake."""

    link_args: T.List[str]
    clib_compiler: 'Compiler'
    env: 'Environment'

    def __init__(self, name: str, kwargs: T.Dict[str, T.Any]):
        self.qtname = name.capitalize()
        self.qtver = name[-1]
        if self.qtver == "4":
            self.qtpkgname = 'Qt'
        else:
            self.qtpkgname = self.qtname

        self.private_headers = T.cast(bool, kwargs.get('private_headers', False))

        self.requested_modules = mesonlib.stringlistify(mesonlib.extract_as_list(kwargs, 'modules'))
        if not self.requested_modules:
            raise DependencyException('No ' + self.qtname + '  modules specified.')

        self.qtmain = T.cast(bool, kwargs.get('main', False))
        if not isinstance(self.qtmain, bool):
            raise DependencyException('"main" argument must be a boolean')

    def _link_with_qtmain(self, is_debug: bool, libdir: T.Union[str, T.List[str]]) -> bool:
        libdir = mesonlib.listify(libdir)  # TODO: shouldn't be necessary
        base_name = 'qtmaind' if is_debug else 'qtmain'
        qtmain = self.clib_compiler.find_library(base_name, self.env, libdir)
        if qtmain:
            self.link_args.append(qtmain[0])
            return True
        return False

    def get_exe_args(self, compiler: 'Compiler') -> T.List[str]:
        # Originally this was -fPIE but nowadays the default
        # for upstream and distros seems to be -reduce-relocations
        # which requires -fPIC. This may cause a performance
        # penalty when using self-built Qt or on platforms
        # where -fPIC is not required. If this is an issue
        # for you, patches are welcome.
        return compiler.get_pic_args()

    def log_details(self) -> str:
        return f'modules: {", ".join(sorted(self.requested_modules))}'

class QtPkgConfigDependency(_QtBase, PkgConfigDependency, metaclass=abc.ABCMeta):

    """Specialization of the PkgConfigDependency for Qt."""

    def __init__(self, name: str, env: 'Environment', kwargs: T.Dict[str, T.Any]):
        _QtBase.__init__(self, name, kwargs)

        # Always use QtCore as the "main" dependency, since it has the extra
        # pkg-config variables that a user would expect to get. If "Core" is
        # not a requested module, delete the compile and link arguments to
        # avoid linking with something they didn't ask for
        PkgConfigDependency.__init__(self, self.qtpkgname + 'Core', env, kwargs)
        if 'Core' not in self.requested_modules:
            self.compile_args = []
            self.link_args = []

        for m in self.requested_modules:
            mod = PkgConfigDependency(self.qtpkgname + m, self.env, kwargs, language=self.language)
            if not mod.found():
                self.is_found = False
                return
            if self.private_headers:
                qt_inc_dir = mod.get_pkgconfig_variable('includedir', {})
                mod_private_dir = os.path.join(qt_inc_dir, 'Qt' + m)
                if not os.path.isdir(mod_private_dir):
                    # At least some versions of homebrew don't seem to set this
                    # up correctly. /usr/local/opt/qt/include/Qt + m_name is a
                    # symlink to /usr/local/opt/qt/include, but the pkg-config
                    # file points to /usr/local/Cellar/qt/x.y.z/Headers/, and
                    # the Qt + m_name there is not a symlink, it's a file
                    mod_private_dir = qt_inc_dir
                mod_private_inc = _qt_get_private_includes(mod_private_dir, m, mod.version)
                for directory in mod_private_inc:
                    mod.compile_args.append('-I' + directory)
            self._add_sub_dependency([lambda: mod])

        if self.env.machines[self.for_machine].is_windows() and self.qtmain:
            # Check if we link with debug binaries
            debug_lib_name = self.qtpkgname + 'Core' + _get_modules_lib_suffix(self.version, self.env.machines[self.for_machine], True)
            is_debug = False
            for arg in self.get_link_args():
                if arg == f'-l{debug_lib_name}' or arg.endswith(f'{debug_lib_name}.lib') or arg.endswith(f'{debug_lib_name}.a'):
                    is_debug = True
                    break
            libdir = self.get_pkgconfig_variable('libdir', {})
            if not self._link_with_qtmain(is_debug, libdir):
                self.is_found = False
                return

        self.bindir = self.get_pkgconfig_host_bins(self)
        if not self.bindir:
            # If exec_prefix is not defined, the pkg-config file is broken
            prefix = self.get_pkgconfig_variable('exec_prefix', {})
            if prefix:
                self.bindir = os.path.join(prefix, 'bin')

    @staticmethod
    @abc.abstractmethod
    def get_pkgconfig_host_bins(core: PkgConfigDependency) -> T.Optional[str]:
        pass

    @abc.abstractmethod
    def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
        pass

    def log_info(self) -> str:
        return 'pkg-config'

class QmakeQtDependency(_QtBase, ConfigToolDependency, metaclass=abc.ABCMeta):

    """Find Qt using Qmake as a config-tool."""

    tool_name = 'qmake'
    version_arg = '-v'

    def __init__(self, name: str, env: 'Environment', kwargs: T.Dict[str, T.Any]):
        _QtBase.__init__(self, name, kwargs)
        self.tools = [f'qmake-{self.qtname}', 'qmake']

        # Add additional constraits that the Qt version is met, but preserve
        # any version requrements the user has set as well. For exmaple, if Qt5
        # is requested, add "">= 5, < 6", but if the user has ">= 5.6", don't
        # lose that.
        kwargs = kwargs.copy()
        _vers = mesonlib.listify(kwargs.get('version', []))
        _vers.extend([f'>= {self.qtver}', f'< {int(self.qtver) + 1}'])
        kwargs['version'] = _vers

        ConfigToolDependency.__init__(self, name, env, kwargs)
        if not self.found():
            return

        # Query library path, header path, and binary path
        stdo = self.get_config_value(['-query'], 'args')
        qvars: T.Dict[str, str] = {}
        for line in stdo:
            line = line.strip()
            if line == '':
                continue
            k, v = line.split(':', 1)
            qvars[k] = v
        # Qt on macOS uses a framework, but Qt for iOS/tvOS does not
        xspec = qvars.get('QMAKE_XSPEC', '')
        if self.env.machines.host.is_darwin() and not any(s in xspec for s in ['ios', 'tvos']):
            mlog.debug("Building for macOS, looking for framework")
            self._framework_detect(qvars, self.requested_modules, kwargs)
            # Sometimes Qt is built not as a framework (for instance, when using conan pkg manager)
            # skip and fall back to normal procedure then
            if self.is_found:
                return
            else:
                mlog.debug("Building for macOS, couldn't find framework, falling back to library search")
        incdir = qvars['QT_INSTALL_HEADERS']
        self.compile_args.append('-I' + incdir)
        libdir = qvars['QT_INSTALL_LIBS']
        # Used by qt.compilers_detect()
        self.bindir = get_qmake_host_bins(qvars)

        # Use the buildtype by default, but look at the b_vscrt option if the
        # compiler supports it.
        is_debug = self.env.coredata.get_option(mesonlib.OptionKey('buildtype')) == 'debug'
        if mesonlib.OptionKey('b_vscrt') in self.env.coredata.options:
            if self.env.coredata.options[mesonlib.OptionKey('b_vscrt')].value in {'mdd', 'mtd'}:
                is_debug = True
        modules_lib_suffix = _get_modules_lib_suffix(self.version, self.env.machines[self.for_machine], is_debug)

        for module in self.requested_modules:
            mincdir = os.path.join(incdir, 'Qt' + module)
            self.compile_args.append('-I' + mincdir)

            if module == 'QuickTest':
                define_base = 'QMLTEST'
            elif module == 'Test':
                define_base = 'TESTLIB'
            else:
                define_base = module.upper()
            self.compile_args.append(f'-DQT_{define_base}_LIB')

            if self.private_headers:
                priv_inc = self.get_private_includes(mincdir, module)
                for directory in priv_inc:
                    self.compile_args.append('-I' + directory)
            libfiles = self.clib_compiler.find_library(
                self.qtpkgname + module + modules_lib_suffix, self.env,
                mesonlib.listify(libdir)) # TODO: shouldn't be necissary
            if libfiles:
                libfile = libfiles[0]
            else:
                mlog.log("Could not find:", module,
                         self.qtpkgname + module + modules_lib_suffix,
                         'in', libdir)
                self.is_found = False
                break
            self.link_args.append(libfile)

        if self.env.machines[self.for_machine].is_windows() and self.qtmain:
            if not self._link_with_qtmain(is_debug, libdir):
                self.is_found = False

    def _sanitize_version(self, version: str) -> str:
        m = re.search(rf'({self.qtver}(\.\d+)+)', version)
        if m:
            return m.group(0).rstrip('.')
        return version

    @abc.abstractmethod
    def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
        pass

    def _framework_detect(self, qvars: T.Dict[str, str], modules: T.List[str], kwargs: T.Dict[str, T.Any]) -> None:
        libdir = qvars['QT_INSTALL_LIBS']

        # ExtraFrameworkDependency doesn't support any methods
        fw_kwargs = kwargs.copy()
        fw_kwargs.pop('method', None)
        fw_kwargs['paths'] = [libdir]

        for m in modules:
            fname = 'Qt' + m
            mlog.debug('Looking for qt framework ' + fname)
            fwdep = QtExtraFrameworkDependency(fname, self.env, fw_kwargs, language=self.language)
            if fwdep.found():
                self.compile_args.append('-F' + libdir)
                self.compile_args += fwdep.get_compile_args(with_private_headers=self.private_headers,
                                                            qt_version=self.version)
                self.link_args += fwdep.get_link_args()
            else:
                self.is_found = False
                break
        else:
            self.is_found = True
            # Used by self.compilers_detect()
            self.bindir = get_qmake_host_bins(qvars)

    def log_info(self) -> str:
        return 'qmake'

class Qt4ConfigToolDependency(QmakeQtDependency):

    def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
        return []

class Qt5ConfigToolDependency(QmakeQtDependency):

    def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
        return _qt_get_private_includes(mod_inc_dir, module, self.version)

class Qt6ConfigToolDependency(QmakeQtDependency):

    def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
        return _qt_get_private_includes(mod_inc_dir, module, self.version)

class Qt4PkgConfigDependency(QtPkgConfigDependency):

    @staticmethod
    def get_pkgconfig_host_bins(core: PkgConfigDependency) -> T.Optional[str]:
        # Only return one bins dir, because the tools are generally all in one
        # directory for Qt4, in Qt5, they must all be in one directory. Return
        # the first one found among the bin variables, in case one tool is not
        # configured to be built.
        applications = ['moc', 'uic', 'rcc', 'lupdate', 'lrelease']
        for application in applications:
            try:
                return os.path.dirname(core.get_pkgconfig_variable('%s_location' % application, {}))
            except mesonlib.MesonException:
                pass
        return None

    def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
        return []

class Qt5PkgConfigDependency(QtPkgConfigDependency):

    @staticmethod
    def get_pkgconfig_host_bins(core: PkgConfigDependency) -> str:
        return core.get_pkgconfig_variable('host_bins', {})

    def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
        return _qt_get_private_includes(mod_inc_dir, module, self.version)

class Qt6PkgConfigDependency(QtPkgConfigDependency):

    @staticmethod
    def get_pkgconfig_host_bins(core: PkgConfigDependency) -> str:
        return core.get_pkgconfig_variable('host_bins', {})

    def get_private_includes(self, mod_inc_dir: str, module: str) -> T.List[str]:
        return _qt_get_private_includes(mod_inc_dir, module, self.version)

qt4_factory = DependencyFactory(
    'qt4',
    [DependencyMethods.PKGCONFIG, DependencyMethods.CONFIG_TOOL],
    pkgconfig_class=Qt4PkgConfigDependency,
    configtool_class=Qt4ConfigToolDependency,
)

qt5_factory = DependencyFactory(
    'qt5',
    [DependencyMethods.PKGCONFIG, DependencyMethods.CONFIG_TOOL],
    pkgconfig_class=Qt5PkgConfigDependency,
    configtool_class=Qt5ConfigToolDependency,
)

qt6_factory = DependencyFactory(
    'qt6',
    [DependencyMethods.PKGCONFIG, DependencyMethods.CONFIG_TOOL],
    pkgconfig_class=Qt6PkgConfigDependency,
    configtool_class=Qt6ConfigToolDependency,
)


text:
#include "irenderable.h"
#include "graphics\texturearray.h"

namespace hle
{
	typedef class ENGINE_API IMesh
		: public IRenderable
	{
	private:
		std::string				m_identifier;
		CTextureArray*			m_textures;
	protected:
		typedef struct VERTEXTYPE
		{
			D3DXVECTOR3 position;
			D3DXVECTOR2 tex_coords;
			D3DXVECTOR3 normal, tangent, binormal;

			VERTEXTYPE( void )
			{
				ZeroMemory( &position, sizeof( position ) );
				ZeroMemory( &tex_coords, sizeof( tex_coords ) );
				ZeroMemory( &normal, sizeof( normal ) );
				ZeroMemory( &tangent, sizeof( tangent ) );
				ZeroMemory( &binormal, sizeof( binormal ) );
			}

			VERTEXTYPE( D3DXVECTOR3 pos, D3DXVECTOR2 tex_coords, D3DXVECTOR3 normal )
				: position( pos ), tex_coords( tex_coords ), normal( normal )
			{
				ZeroMemory( &tangent, sizeof( tangent ) );
				ZeroMemory( &binormal, sizeof( binormal ) );
			}

			VERTEXTYPE( D3DXVECTOR3 pos, D3DXVECTOR2 tex_coords, D3DXVECTOR3 normal, D3DXVECTOR3 tangent, D3DXVECTOR3 binormal )
				: position( pos ), tex_coords( tex_coords ), normal( normal ), tangent( tangent ), binormal( binormal )
			{
			}
		} VERTEXTYPE, *LPVERTEXTYPE;

		typedef struct MESHTYPE
		{
			float	x, y, z;
			float	tu, tv;
			float	nx, ny, nz;
			float	tx, ty, tz;
			float	bx, by, bz;
		} MESHTYPE, *LPMESHTYPE;

		typedef struct TMPVERTEXTYPE
		{
			float	x, y, z;
			float	tu, tv;
			float	nx, ny, nz;
		} TMPVERTEXTYPE, *LPTMPVERTEXTYPE;

		typedef	struct VECTORTYPE
		{
			float x, y, z;
		} VECTORTYPE, *LPVECTORTYPE;

		std::vector<VERTEXTYPE>	m_vertices;

		LPMESHTYPE				m_mesh;

		virtual	bool	Load( CHAR* filename );

		void	CalculateVectors( void );
		void	CalculateTangentBinormal(TMPVERTEXTYPE, TMPVERTEXTYPE, TMPVERTEXTYPE, VECTORTYPE&, VECTORTYPE&);
		void	CalculateNormal(VECTORTYPE, VECTORTYPE, VECTORTYPE&);
	public:
		IMesh ( void );
		~IMesh( void );

		READONLY_PROPERTY(CTextureArray*, textures);
		GET(textures)	{ return m_textures; }

		PROPERTY(std::string, ID);
		GET(ID)	{ return m_identifier; }
		SET(ID)	{ m_identifier = value;}

		virtual	bool	SetTexture( WCHAR* filename );
		// initialize with multiple textures
		virtual bool	Initialize( CHAR* model ) = 0;

		virtual void	Release	( void );
		virtual	void	Render	( void ) = 0;	// this method will be defined in each model class

	} MESH, *LPMESH;

	typedef std::map<std::string, LPMESH>	hle_meshs;
	typedef std::pair<std::string, LPMESH>	hle_mesh;
};


text:
All the necessary to provision, configure and manage my home lab.

Before using the home lab, you initialize the environments by executing
a manual process. After the initalization process completes,
automated processes take care of applying provisioning and
configuration changes to the environments.

## Dependencies

To interact with the home lab, you need the following tools:

- [Git](https://git-scm.com/) (tested with version `2.25.0`).
- An OCI container runtime, such as Docker. Tested with Docker 20.10.
- During the bootstrap phase, the Home Lab also supports hosts where there's no container engine.

## Initialize the environment

To initialize the edge environment, you execute the first initialization process
using a seed device. Besides this initialization phase that may require a manual
intervention, devices in the edge envirnment auto-configure themselves when they
start.

### Initialize the edge environment with the seed device

To provision the edge environment, you use a seed device.

As soon as the seed device detects that the edge environment initialization
process is completed, and there are enough nodes, servers, and service
instances to back the seed device up, the seed device loads and the
configuration that non-seed devices use, and applies that configuration to
itself. This approach has two benefits:

1. Avoid circular dependencies. The on premises environment needs minimal,
    pre-existing infrastructure to complete the initialization process.
1. Avoid special-purpose devices. By applying the general-purpose configuration
    to the seed device after the initialization process, you avoid introducing
    ad-hoc components in the environment.

After the edge environment initialization process is completed, the seed device
has no special purpose or status, and you can use that seed device as any other
device in the edge environment.

The seed device has as few external dependencies as possible. The seed
device requires:

1. A connection to an IP network that can route packets to the
    internet.
1. An IP address to statically assign to the main network interface of the seed
    device.

#### Initialize the seed device

The current version of the home lab uses a Raspberry Pi 4 as a seed device. To
initialize the seed device:

1. Update and configure the bootloader.
1. Prepare the seed device boot disk and
1. Boot the seed device.

#### Update and configure the Raspberry Pi 4 bootloader

To update the bootloader on the [Raspberry Pi 4 EEPROM](https://www.raspberrypi.com/documentation/computers/raspberry-pi.html#raspberry-pi-4-boot-eeprom)
and configure the [boot order](https://www.raspberrypi.com/documentation/computers/raspberry-pi.html#BOOT_ORDER)
when not using Raspberry Pi OS, do the following:

1. Download the latest release of [rpi-eeprom](https://github.com/raspberrypi/rpi-eeprom/releases).
    There are different boot order configurations available, as configured
    [here](https://github.com/raspberrypi/rpi-eeprom/tree/master/imager).
1. Flash the bootloader disk image on a removable flash drive. For more information about flashing Raspberry Pi OS
    images to a SD card, refer to [Raspberry Pi: Getting started](https://www.raspberrypi.org/documentation/computers/getting-started.html).
1. Insert the SD card in a powered off Raspberry Pi 4.
1. Wait for the activity LED to steadily flash green.
1. Power the Raspberry Pi off.

#### Prepare the seed device boot disk

To initialize the seed device, do the following:

1. Download the OS installer disk image.
1. Flash the OS installer disk image on a removable flash drive:

    On Linux:

    ```sh
    sudo dd bs=4M if=[PATH_TO_ISO] of=[USB_FLASH_DRIVE] conv=fdatasync status=progress
    ```

    On MacOS:

    ```sh
    diskutil unmountDisk [USB_FLASH_DRIVE]
    sudo dd bs=4m if=[PATH_TO_IMAGE] of=[USB_FLASH_DRIVE]; sync
    sudo diskutil eject [USB_FLASH_DRIVE]
    ```

1. Download the OS installer configuration disk image.
1. Flash the OS installer configuration disk image on a dedicated, removable flash drive adapting the commands described
    in the previous steps. For more information about flashing Raspberry Pi OS images to a SD card, refer to
    [Raspberry Pi: Getting started](https://www.raspberrypi.org/documentation/computers/getting-started.html).

#### Boot the seed device

After preparing the seed device boot disk, insert it into the seed device and boot the seed device
for the first time. The seed device will autoconfigure itself.

### Provision new hosts

When provisioning a new host, do the following:

1. Set a unique hostname for the new host.
1. Add the new host to the Ansible inventory.

#### Configure Raspberry Pi nodes

To update the configuration of a Raspberry Pis running Raspberry Pi OS, refer to
[Raspberry Pi Documentation](https://www.raspberrypi.com/documentation/computers/configuration.html).

For example, you may need to change the hostname of a newly provisioned node
before adding it to the set of automatically configured nodes.

### Configure hosts with Ansible

For newly provisioned hosts, you might have to authenticate a SSH connection using
a passowrd instead of a key. To authenticate with a password, add the
`--ask-pass --connection paramiko` switches to the Ansible command you're running.

Note: Using [Paramiko](https://www.paramiko.org/) lets you use password authentication
without having the `sshpass` program installed on the host that runs Ansible.

To run Ansible, use the `scripts/run-ansible.sh` script. This script provides a
thin wrapper that takes care of setting up either a container (preferred) or a
Python virtual environment to run Ansible.

#### Ansible execution examples

These examples assume that the current working directory is the root of this repository.

To run `ansible-playbook` against the hosts listed in an inventory:

```shell
scripts/run-ansible.sh "ansible-playbook --inventory docker/ansible/etc/ansible/inventory/hosts.yml docker/ansible/etc/ansible/playbooks/main.yaml"
```

To gather all the facts about a single host:

```shell
scripts/run-ansible.sh "ansible -m ansible.builtin.setup --user pi -i 'hostname.tld,' all"
```

#### Copy Jinja templates as they are

If you need to copy Jinja templates with the Ansible Template Module, you can
configure Ansible to change the variable start and end prefixes inside the template
by adding a special header.

For example:

```yaml
#jinja2:variable_start_string:'[%', variable_end_string:'%]'
```

Changes the default variable start and end prefixes from `{{` and `}}` to `[%` and `%]`.

### Add hosts to the Tailscale network

The automated provisioning and configuration process takes care of setting up
the Tailscale CLI.

To add a device to the Tailscale network, do the following:

1. From a shell on the host to add to the Tailscale network, run:

    ```shell
    sudo tailscale up
    ```

    and follow the instructions to authenticate
2. (optional) Disable [Tailscale key expiration](https://tailscale.com/kb/1028/key-expiry/)

### DNS configuration

In this section, we describe the configuration of DNS servers, zones, and resource records.

#### DNS servers and zones

This environment contains two private DNS servers:

- A CoreDNS instance (`ns1.lab.ferrari.how`) that acts as the authoritative name server for the main DNS zone: `lab.ferrari.how`.
- A dnsmasq instance running on the default gateway and responds to DNS queries for the `edge.lab.ferrari.how` zone and returns
    authoritative answers from DHCP leases ([source](https://lists.thekelleys.org.uk/pipermail/dnsmasq-discuss/2008q4/002670.html)),
    even if it doesn't run as an authoritative name server for the `edge.lab.ferrari.how` zone.
    This dnsmasq instance also handles DHCP for the main subnet.

### Configure network shares

To allow access to Samba network shares, do the following:

1. Create a Linux system user.
1. Add the user to the Samba database:

    ```shell
    sudo smbpasswd -a "${USER}"
    ```

## Monitoring

To monitor the status of the home lab, the automated provisioning and configuration
process deploy a monitoring agent on each home lab node, and a backend to collect
data coming from the monitoring agents.

### Import Grafana dashsboards

In its current state, Grafana doesn't support automatic import of dashboards that
a datasource ships, so you need to import those dashboards manually. To import
Grafana dashboards that ship with a datasource, do the following:

1. Open Grafana.
2. Open the datasource settings
3. Select a datasource.
4. Open the `Dashboards` panel.
5. Import the dashboards.

## Development environment

In this section, you set up a development environment for the home lab.

### Generate the templated files

To avoid duplications, a template generator produces files from templates.
To generate templated files, do the following:

```sh
scripts/generate-templated-files.sh
```

After the generator produces the files, commit any updates to the generated files.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<title>
DOX XSS Aktif Tarama Kuralı
</title>

DOX XSS Aktif Tarama Kuralı

DOM XSS açıklarının tespiti için bir Aktif Tarama kuralı.

It launches browser windows and sends attack payloads to all of the relevant DOM elements.

As it launches browser windows it will take significantly longer than other (non browser based) rules.

This version supports Firefox (the default) and Chrome. They can be run with GUI or headless (default), it can be changed with
the rule rules.domxss.browserid, via the Options 'Rule configuration' panel, with values
firefox, firefox-headless, chrome and chrome-headless.

The following Attack Strengths are supported, and related directly to the number of attack payloads used
for URL fragment and form input field injections (eg: http://example.com/index.html?foo=bar#injection):

LOW: 1 attack payloads

MEDIUM: 3 attack payloads

YÜKSEK: 6 saldırı yükü

INSANE: 9 attack payloads

The scanner will also attempt URL/query parameter injections which are not impacted by the selected strength.

Kural, yalnızca LOW Uyarı eşiği kullanılmadığı sürece, düğüm başına bir DOM XSS güvenlik açığını bildirir; bu durumda belirtilen yüklerin tümünü denemeye devam eder.

Latest code: DomXssScanRule.java


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="../../node_modules/jquery-colorbox/example1/colorbox.css" />
    <link rel="stylesheet" href="../../node_modules/swipebox/src/css/swipebox.min.css" />
    <link rel="stylesheet" href="../../dist/css/justifiedGallery.css" />

Destroy test

        <button id="callJG">JG</button>
        <button id="callJGDestroy">JG Destroy</button>

non created caption


text:
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.

using System;
using DotSpatial.Modeling.Forms.Parameters;

namespace DotSpatial.Modeling.Forms.Elements
{
    /// <summary>
    /// String Element for use in the tool dialog.
    /// </summary>
    internal partial class StringElement : DialogElement
    {
        #region  Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="StringElement"/> class.
        /// </summary>
        /// <param name="param">The parameter this element represents</param>
        public StringElement(StringParam param)
        {
            // Needed by the designer
            InitializeComponent();
            GroupBox.Text = param.Name;

            // We save the parameters passed in
            Param = param;
            SetupDefaultLighting();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the Parameter that the element represents.
        /// </summary>
        public new StringParam Param
        {
            get
            {
                return (StringParam)base.Param;
            }

            set
            {
                base.Param = value;
            }
        }

        #endregion

        #region Methods

        /// <inheritdoc />
        public override void Refresh()
        {
            SetupDefaultLighting();
        }

        private void SetupDefaultLighting()
        {
            // We load the default parameters
            if (Param.DefaultSpecified)
            {
                textBox1.Text = Param.Value;
                Status = ToolStatus.Ok;
                LightTipText = ModelingMessageStrings.ParameterValid;
            }
            else
            {
                Status = ToolStatus.Empty;
                LightTipText = ModelingMessageStrings.ParameterInvalid;
            }
        }

        /// <summary>
        /// When the text box is clicked this event fires.
        /// </summary>
        /// <param name="sender">The sender that raised the event.</param>
        /// <param name="e">The event args.</param>
        private void TextBox1Click(object sender, EventArgs e)
        {
            OnClick(e);
        }

        /// <summary>
        /// This changes the color of the light and the tooltip of the light based on the status of the text in the box
        /// </summary>
        /// <param name="sender">The sender that raised the event.</param>
        /// <param name="e">The event args.</param>
        private void TextBox1TextChanged(object sender, EventArgs e)
        {
            Param.Value = textBox1.Text;
        }

        #endregion
    }
}


text:
using System;

using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.EventSystems;

namespace Assets.Scripts.Player {
    public class PlayerChat : NetworkBehaviour {

        public bool focusedOnInput = false;
        public Text chatText;
        public InputField chatInput;

        PlayerInput playerInput;

        void Start() {
            chatText = GameObject.Find("Chat text").GetComponent<Text>();
            chatInput = GameObject.Find("Chat input").GetComponent<InputField>();

            playerInput = GetComponent<PlayerInput>();
        }

        public void FocusOnInput() {
            chatInput.gameObject.SetActive(true);
            SetZ(0);
            chatInput.ActivateInputField();

            focusedOnInput = true;
        }

        public void UnfocusOnInput() {
            chatInput.gameObject.SetActive(false);
            SetZ(-10000);
            chatInput.DeactivateInputField();

            focusedOnInput = false;
        }

        void OnGUI() {
            if (isLocalPlayer && Input.GetAxisRaw("Submit") > 0) {
                if (chatInput.text != "") {
                    SendMessage(chatInput.text.Replace("<","<").Replace(">",">"));
                }
                chatInput.text = "";
                SetZ(-10000);
                chatInput.gameObject.SetActive(false);
            }
        }

        void SendMessage(string message) {
            message = "<color=" + GetComponent<Player>().lobbyPlayer.team.name + ">" + GetComponent<Player>().lobbyPlayer.nickname + ": </color>" + message;
            CmdSendMessage(message);
            if (isServer) {
                chatText.text += "\n" + message;
            }
        }

        [Command]
        void CmdSendMessage(string message) {
            RpcReceiveMessage(message);
        }

        [ClientRpc]
        void RpcReceiveMessage(string message) {
            chatText.text += "\n" + message;
        }

        void SetZ(float value) {
            var pos = chatInput.transform.localPosition;
            pos.z = value;
            chatInput.transform.localPosition = pos;
        }
    }
}


text:
<?php defined('SYSPATH') or die('No direct access allowed.');

class Model_Visa_City extends ORM {

     public function deleteClear()
	 {
		 $this->delete();
	 }
}


text:
package org.omg.CORBA;

import gnu.CORBA.typecodes.PrimitiveTypeCode;

import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.OutputStream;
import org.omg.CORBA.portable.Streamable;

/**
 * A holder for CORBA float that is mapped into
 * java float.
 *
 * The holders have several application areas. The end user usually
 * sees them implementing CORBA methods where the primitive type
 * is passed by reference. While CORBA (or, for example, C) supports
 * this, the java does not and a wrapper class is required.
 *
 * @author Audrius Meskauskas (AudriusA@Bioinformatics.org)
 */
public final class FloatHolder
  implements Streamable
{
  /**
   * The default type code for this holder.
   */
  private static final TypeCode t_float =
    new PrimitiveTypeCode(TCKind.tk_float);

  /**
   * The float (CORBA float) value,
   * held by this FloatHolder.
   */
  public float value;

  /**
   * Constructs an instance of FloatHolder,
   * initializing {@link #value} to 0.0.
   */
  public FloatHolder()
  {
  }

  /**
   * Constructs an instance of FloatHolder,
   * initializing {@link #value} to the given float.
   *
   * @param initial_value a value that will be assigned to the
   * {@link #value} field.
   */
  public FloatHolder(float initial_value)
  {
    value = initial_value;
  }

  /**
   * Fill in the {@link value } field by reading the required data
   * from the given stream. For float, the functionality
   * is delegated to
   * {@link org.omg.CORBA.portable.InputStream#read_float}.
   *
   * @param input the input stream to read from.
   */
  public void _read(InputStream input)
  {
    value = input.read_float();
  }

  /**
   * Returns the TypeCode, corresponding the CORBA type that is stored
   * using this holder.
   */
  public TypeCode _type()
  {
    return t_float;
  }

  /**
   * Write the {@link value } field to the given stream.
   * For float, the functionality
   * is delegated to
   * {@link org.omg.CORBA.portable.OutputStream#write_float(float) }.
   *
   * @param output the output stream to write into.
   */
  public void _write(OutputStream output)
  {
    output.write_float(value);
  }
}


text:
require 'cinch/plugins/lastactive/version'
require 'cinch/plugins/lastactive'


text:
$(function(){
  Dropzone.autoDiscover = false;

  $("#my-dropzone").dropzone({
    maxFilesize: 2,
    addRemoveLinks: true,
    paramName: 'post[image]',
    success: function(file, response) {
			$(file.previewElement).find('.dz-remove').attr('id', response.postId);
			$(file.previewElement).addClass('dz-success');
		},
    removedfile: function(file) {
			var id = $(file.previewTemplate).find('.dz-remove').attr('id');

			$.ajax({
				type: 'DELETE',
				url: "/posts/" + id,
				success: function(data) {
					console.log(data.message);
				}
			});

			var previewElement;
			return (previewElement = file.previewElement) != null ? (previewElement.parentNode.removeChild(file.previewElement)) : (void 0);
		},
		init: function() {
			var me = this;

			$.get("<%= Rails.application.routes.url_helpers.list_posts_path %>", function(data) {
				$.each(data.images, function(key, value) {
					if (data.images != undefined && data.images.length > 0) {
						me.emit("addedfile", value);
						me.emit("thumbnail", value, value.src);
						me.emit("complete", value);

						$(value._removeLink).attr("id", value.id);
					}
				});
			});
		}
  });
});


text:
function checkCookie(){

	var currentUser = Parse.User.current();
	if(currentUser){
		window.location = ('pages/main.html');
	}
}

Parse.initialize("Gy5zoQPReNBVWCK3JP9EUSnFpBAlmeSfg5deDtCq", "eYfKlYkY777qlJg0eMUqtUQYmXF5tlqs6uUlbhug");

$("button#submit").click( function() {
    document.getElementById("loginButton").innerHTML='';
  if( $("#username").val() == "" || $("#password").val() == "" ){
      document.getElementById("card").style.display = "block";
      document.getElementById("loginButton").innerHTML='Logg inn';
    $("div#loginmsg").html('Vennligst skriv brukernavn og passord');
  }
	else{

		Parse.User.logIn($("#username").val(), $("#password").val(), {
		  success: function(user) {
		    window.location = ('pages/main.html');
		  },
		  error: function(user, error) {
              document.getElementById("card").style.display = "block";
              document.getElementById("loginButton").innerHTML='Logg inn';
		    $("div#loginmsg").html('Feil brukernavn og/eller passord');
		  }
		});
	}

	$("#loginform").submit( function() {
	   return false;
	});

});


text:
module Ci
  class PipelinePresenter < Gitlab::View::Presenter::Delegated
    include Gitlab::Utils::StrongMemoize
    include ActionView::Helpers::UrlHelper

    # We use a class method here instead of a constant, allowing EE to redefine
    # the returned `Hash` more easily.
    def self.failure_reasons
      { config_error: 'CI/CD YAML configuration error!' }
    end

    presents :pipeline

    def failed_builds
      return [] unless can?(current_user, :read_build, pipeline)

      strong_memoize(:failed_builds) do
        pipeline.builds.latest.failed
      end
    end

    def failure_reason
      return unless pipeline.failure_reason?

      self.class.failure_reasons[pipeline.failure_reason.to_sym] ||
        pipeline.failure_reason
    end

    def status_title
      if auto_canceled?
        "Pipeline is redundant and is auto-canceled by Pipeline ##{auto_canceled_by_id}"
      end
    end

    NAMES = {
      merge_train: s_('Pipeline|Merge train pipeline'),
      merged_result: s_('Pipeline|Merged result pipeline'),
      detached: s_('Pipeline|Detached merge request pipeline')
    }.freeze

    def name
      # Currently, `merge_request_event_type` is the only source to name pipelines
      # but this could be extended with the other types in the future.
      NAMES.fetch(pipeline.merge_request_event_type, s_('Pipeline|Pipeline'))
    end

    def ref_text
      if pipeline.detached_merge_request_pipeline?
        _("for %{link_to_merge_request} with %{link_to_merge_request_source_branch}")
          .html_safe % {
            link_to_merge_request: link_to_merge_request,
            link_to_merge_request_source_branch: link_to_merge_request_source_branch
          }
      elsif pipeline.merge_request_pipeline?
        _("for %{link_to_merge_request} with %{link_to_merge_request_source_branch} into %{link_to_merge_request_target_branch}")
          .html_safe % {
            link_to_merge_request: link_to_merge_request,
            link_to_merge_request_source_branch: link_to_merge_request_source_branch,
            link_to_merge_request_target_branch: link_to_merge_request_target_branch
          }
      elsif pipeline.ref && pipeline.ref_exists?
        _("for %{link_to_pipeline_ref}")
        .html_safe % { link_to_pipeline_ref: link_to_pipeline_ref }
      elsif pipeline.ref
        _("for %{ref}").html_safe % { ref: plain_ref_name }
      end
    end

    def all_related_merge_request_text
      if all_related_merge_requests.none?
        'No related merge requests found.'
      else
        _("%{count} related %{pluralized_subject}: %{links}" % {
          count: all_related_merge_requests.count,
          pluralized_subject: 'merge request'.pluralize(all_related_merge_requests.count),
          links: all_related_merge_request_links.join(', ')
        }).html_safe
      end
    end

    def link_to_pipeline_ref
      link_to(pipeline.ref,
        project_commits_path(pipeline.project, pipeline.ref),
        class: "ref-name")
    end

    def link_to_merge_request
      return unless merge_request_presenter

      link_to(merge_request_presenter.to_reference,
        project_merge_request_path(merge_request_presenter.project, merge_request_presenter),
        class: 'mr-iid')
    end

    def link_to_merge_request_source_branch
      merge_request_presenter&.source_branch_link
    end

    def link_to_merge_request_target_branch
      merge_request_presenter&.target_branch_link
    end

    private

    def plain_ref_name
      content_tag(:span, pipeline.ref, class: 'ref-name')
    end

    def merge_request_presenter
      strong_memoize(:merge_request_presenter) do
        if pipeline.triggered_by_merge_request?
          pipeline.merge_request.present(current_user: current_user)
        end
      end
    end

    def all_related_merge_request_links
      all_related_merge_requests.map do |merge_request|
        mr_path = project_merge_request_path(merge_request.project, merge_request)

        link_to "#{merge_request.to_reference} #{merge_request.title}", mr_path, class: 'mr-iid'
      end
    end

    def all_related_merge_requests
      strong_memoize(:all_related_merge_requests) do
        pipeline.ref ? pipeline.all_merge_requests_by_recency.to_a : []
      end
    end
  end
end

Ci::PipelinePresenter.prepend_if_ee('EE::Ci::PipelinePresenter')


text:
'use strict';

// Simple function wrapper that batches Node-style calls.

// Batching is achieved by wrapping a function in logic that records calls in
// a batch for some time, then calls that function once with the accumulated
// batch, giving it an opportunity to process all the calls efficiently at
// once. Unbatching takes a batch of calls, applies them individually to a
// function, then returns a batch of results.

const _ = require('underscore');
const yieldable = require('abacus-yieldable');
const transform = require('abacus-transform');

const map = _.map;
const identity = _.identity;
const initial = _.initial;
const zip = _.zip;
const last = _.last;
const extend = _.extend;
const isFunction = _.isFunction;
const object = _.object;
const pairs = _.pairs;
const functions = _.functions;
const bind = _.bind;
const filter = _.filter;
const values = _.values;
const flatten = _.flatten;
const groupBy = _.groupBy;
const sortBy = _.sortBy;
const defaults = _.defaults;

// Setup debug log
const debug = require('abacus-debug')('abacus-batch');

// Return a function that records calls for some time and presents the whole
// list of calls later to the given batch function
const batchifyfn = (fn, delay, max, size) => {
  // Use a default time delay of 20 msec and a default batch size of 100
  const opt = defaults({
    timeout: delay,
    msize: max,
    csize: size
  }, {
    timeout: parseInt(process.env.BATCH_DELAY) || 20,
    msize: parseInt(process.env.BATCH_SIZE) || 100,
    csize: () => 1
  });

  // Convert to a function with callback
  const fcb = yieldable.functioncb(fn);

  // Warning: bcalls and bsize are mutable variables, but that's by design
  // as we're using them to record and accumulate function calls
  let bcalls = [];
  let bsize = 0;

  // Warning: tid is a mutable variable, by design again as it's used to
  // record the id of the batching timeout
  let tid;

  // Flush a batch of recorded calls
  const flush = () => {
    const fcalls = bcalls;
    // Warning: mutating variables bcalls and bsize, by design again
    bcalls = [];
    bsize = 0;

    // Pass the list of calls to the batch function
    debug(
      'Calling batch function %s with %d batched calls', name, fcalls.length);
    fcb(map(fcalls, (call) => initial(call)), (err, vals) => {
      if(err)
        debug('Returning %d batch function results with error %o',
          vals ? vals.length : 0, err);
        else
        debug('Returning %d batch function results',
          vals ? vals.length : 0);

      // Pass each call result to the corresponding callback
      return map(zip(fcalls, vals),
        (call) => last(call[0]).apply(undefined, err ? [err] : call[1]));
    });
  };

  // Determine the application function name
  const name = fcb.fname || fcb.name;

  const wrapper = function() {
    // Record each call arguments in our list of calls
    const call = map(arguments, identity);
    debug('Recording function call to %s', name);
    // Warning: mutating variable bcalls, by design
    bcalls.push(call);

    // Add the size of each call to the batch size
    bsize += opt.csize(name, call);

    // Use a timer to decide  when to pass the list of calls to the batch
    // function
    if(bcalls.length === 1)
      tid = setTimeout(flush, opt.timeout);

    if(bsize >= opt.msize) {
      if(tid) clearTimeout(tid);
      flush();
    }
  };

  // Store the application function name in the wrapper function
  wrapper.fname = name;

  return wrapper;
};

// Return a function that organizes a batch of calls in groups, applies each
// group of calls and assembles the results
const groupfn = (fn, group) => {

  // Convert the given functions to functions with callback
  const fcb = yieldable.functioncb(fn);
  const gcb = yieldable.functioncb(group);

  return (calls, cb) => {
    // Build a map of call requests to target group keys
    transform.map(calls, (call, i, calls, mcb) => {
      gcb(call, (err, k) => err ? mcb(err) : mcb(undefined, {
        i: i,
        call: call,
        k: k
      }));

    }, (err, maps) => {
      if(err) return cb(err);

      // Group the call maps by group key
      const groups = values(groupBy(maps, (map) => map.k));

      // Apply the requested batch function to each group of call requests
      transform.map(groups, (gmaps, i, groups, mcb) => {

        // Return a zip of the call requests and corresponding results
        fcb(map(gmaps, (gmap) => gmap.call),
          (err, gres) => err ? mcb(err) : mcb(undefined, zip(gmaps, gres)));

      }, (err, gres) => {
        if(err) return cb(err);

        // Assemble the results into a single list of results ordered
        // like the call requests
        cb(undefined, map(
          sortBy(flatten(gres, true), (res) => res[0].i), (res) => res[1]));
      });
    });
  };
};

// Return a function that takes a list of calls, applies each individual call
// to a function and returns a list of results
const unbatchify = (fn) => {
  // Convert to a function with callback
  const fcb = yieldable.functioncb(fn);

  return (calls, cb) => {
    debug('Applying batch of %d function calls', calls.length);
    // Warning: count is a mutable variable, but that's by design as we
    // need to count results from the individual function calls
    let count = 0;
    // Warning: count is a mutable variable, but that's by design as we
    // need to collect results from the individual function calls
    let vals = [];

    // Apply each function call
    map(calls, (call, i) => {
      fcb.apply(undefined, call.concat([(err, val) => {
        // Collect function call result
        debug('Collecting function result %d', i);
        // Warning: mutating variable vals
        vals[i] = [err, val];
        // Warning: mutating variable count
        count++;
        // Call back when we've collected all the results
        if(count === calls.length) {
          debug('Calling back with %d batch function results', count);
          cb(undefined, vals);
        }
      }]));
    });
  };
};

// Bind a function to an object while retaining the function name
const nbind = (o, k) => extend(bind(o[k], o), {
  fname: (o.name || o.fname ? (o.name || o.fname) + '.' : '') + (o[k].name ||
      o[k].fname || k)
});

// Convert an application function using batchifyfn, if the given function is
// a module then convert all the functions exported by the module named like
// batch_* as well.
const batchify = (fn, delay, max, size) => extend(isFunction(fn) ?
    batchifyfn(fn, delay, max, size) : {}, object(pairs(fn)),
      object(map(filter(functions(fn), (k) => /^batch_/.test(k)),
        (k) => [k.substr(6), batchifyfn(nbind(fn, k), delay, max, size)])));

// Export our public functions
module.exports = batchify;
module.exports.batchify = batchify;
module.exports.unbatchify = unbatchify;
module.exports.groupBy = groupfn;


text:
shared_examples 'new issuable record that supports quick actions' do
  let!(:project) { create(:project, :repository) }
  let(:user) { create(:user).tap { |u| project.add_maintainer(u) } }
  let(:assignee) { create(:user) }
  let!(:milestone) { create(:milestone, project: project) }
  let!(:labels) { create_list(:label, 3, project: project) }
  let(:base_params) { { title: 'My issuable title' } }
  let(:params) { base_params.merge(defined?(default_params) ? default_params : {}).merge(example_params) }
  let(:issuable) { described_class.new(project, user, params).execute }

  before do
    project.add_maintainer(assignee)
  end

  context 'with labels in command only' do
    let(:example_params) do
      {
        description: "/label ~#{labels.first.name} ~#{labels.second.name}\n/unlabel ~#{labels.third.name}"
      }
    end

    it 'attaches labels to issuable' do
      expect(issuable).to be_persisted
      expect(issuable.label_ids).to match_array([labels.first.id, labels.second.id])
    end
  end

  context 'with labels in params and command' do
    let(:example_params) do
      {
        label_ids: [labels.second.id],
        description: "/label ~#{labels.first.name}\n/unlabel ~#{labels.third.name}"
      }
    end

    it 'attaches all labels to issuable' do
      expect(issuable).to be_persisted
      expect(issuable.label_ids).to match_array([labels.first.id, labels.second.id])
    end
  end

  context 'with assignee and milestone in command only' do
    let(:example_params) do
      {
        description: %(/assign @#{assignee.username}\n/milestone %"#{milestone.name}")
      }
    end

    it 'assigns and sets milestone to issuable' do
      expect(issuable).to be_persisted
      expect(issuable.assignees).to eq([assignee])
      expect(issuable.milestone).to eq(milestone)
    end
  end

  describe '/close' do
    let(:example_params) do
      {
        description: '/close'
      }
    end

    it 'returns an open issue' do
      expect(issuable).to be_persisted
      expect(issuable).to be_open
    end
  end
end


text:
class PretendeesController < ApplicationController

  def new
    @user = current_user
  end

  def create
    @user = current_user
    @pretendee = Pretendee.new(pretendee_params)
    @pretendee.image = "https://twitter.com/" + @pretendee.twitter.gsub(' ', '') + "/profile_image?size=original"
    @pretendee.save
    PretendeePropertiesHydrator.new(@pretendee.id)

    respond_to do |format|
      format.html { topic.save ? (redirect_to user_path(current_user)) : (render :new) }
      format.js { }
    end
  end

  def show
    @pretendee = Pretendee.find(params['id'])
    @topic = Topic.new
    @user = current_user
    @report = @pretendee.report || Report.new
  end

  def update
    @pretendee = Pretendee.find(params['id'])
    @pretendee.update(pretendee_params)
    redirect_to user_pretendee_path(current_user, @pretendee)
  end

  def destroy
    @pretendee = Pretendee.find(params['id'])
    @pretendee.destroy

    respond_to do |format|
      format.html {redirect_to user_path(User.find(params['user_id']))}
      format.js{}
    end
  end

  private
    def pretendee_params
      params.require(:pretendee).permit(:twitter, :user_id, :name)
    end
end


text:
FROM openjdk:8-jdk-alpine as installforge

# --------------
# Define version
# --------------
ARG VERSION=latest

# ---------------------------------
# Download and install forge server
# ---------------------------------
RUN apk add --update --no-cache libxml2-utils curl \
 && if [ "$VERSION" = "latest" ]; then \
      export VERSION=$( curl "http://files.minecraftforge.net/maven/net/minecraftforge/forge/maven-metadata.xml" | xmllint --xpath "/metadata/versioning/release/text()" - ) \
    ; else \
      export VERSION=$( curl "http://files.minecraftforge.net/maven/net/minecraftforge/forge/maven-metadata.xml" | xmllint --xpath "/metadata/versioning/versions/version[starts-with(text(),'${VERSION}')][last()]/text()" - ) \
    ; fi \
 && cd /tmp \
 && mkdir installer \
 && curl -o /tmp/installer/forge-install.jar "https://files.minecraftforge.net/maven/net/minecraftforge/forge/${VERSION}/forge-${VERSION}-installer.jar" \
 && java -jar /tmp/installer/forge-install.jar --installServer \
 && mv /tmp/forge-*.jar /tmp/forge.jar

#####################
# Build Start.class #
#####################
FROM openjdk:8-jdk-alpine as starter

# ------------------
# Compile Start.java
# ------------------
RUN apk add --update --no-cache wget \
 && cd /tmp/ \
 && wget https://raw.githubusercontent.com/marcermarc/DockerMinecraft/master/StartProgram/Start.java \
 && javac Start.java \
 && chmod +x Start.class

#######
# Run #
#######
FROM alpine:latest

LABEL maintainer "docker@marcermarc.de"

# -----------------------------------------------------------------------------------------------------------
# Default extra params from:
#  https://aquifermc.org/threads/optimizing-paper-remove-lag-spikes-fix-tps-improve-performance.101/#post-822
# Set the classpath can start the Start.class
# -----------------------------------------------------------------------------------------------------------
ENV WORKDIR="/mnt/minecraft" \
  COMMAND="java -Xmx2G -Xms2G -XX:+UseG1GC -XX:+UnlockExperimentalVMOptions -XX:MaxGCPauseMillis=100 -XX:+DisableExplicitGC -XX:TargetSurvivorRatio=90 -XX:G1NewSizePercent=50 -XX:G1MaxNewSizePercent=80 -XX:InitiatingHeapOccupancyPercent=10 -XX:G1MixedGCLiveThresholdPercent=50 -XX:+AggressiveOpts -XX:+AlwaysPreTouch -XX:+UseLargePagesInMetaspace -d64 -Dfile.encoding=UTF-8 -jar /opt/minecraft/forge.jar nogui" \
  CLASSPATH=/opt/start

# --------------------------------
# Copy files from the build images
# --------------------------------
COPY --from=installforge /tmp/*.jar /opt/minecraft/
COPY --from=installforge /tmp/libraries/ /opt/minecraft/libraries
COPY --from=starter /tmp/*.class /opt/start/

# ------------------
# Add user minecraft
# ------------------
RUN mkdir -p /mnt/minecraft \
 && apk add --no-cache openjdk8-jre-base \
 && adduser -D minecraft -h /opt \
 && chown -R minecraft /mnt/minecraft /opt \
 && chmod -R 777 /mnt/minecraft /opt

# ------------
# Expose ports
# ------------
EXPOSE 25565:25565/tcp 25565:25565/udp

# -------------
# Define volume
# -------------
VOLUME ["/mnt/minecraft"]

# ----------------
# Set startup user
# ----------------
USER minecraft

# ---------------------
# Start the Start.class
# ---------------------
ENTRYPOINT ["java", "Start"]


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Datacenter Automation Suite</title>
    <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/admin-lte/2.4.2/css/AdminLTE.min.css"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/admin-lte/2.4.2/css/skins/_all-skins.min.css"/>

    <link rel="stylesheet" href="{{mix('/css/app.css')}}">

    @yield('css')

    {{--<search-box></search-box>--}}
    @if (!Auth::guest())

                    DCAS

                        Toggle navigation

                                    {!! Auth::user()->name !!}

                                            {!! Auth::user()->name !!}
                                            Member since {!! Auth::user()->created_at->format('M. Y') !!}

                                            Profile

                                                Sign out

                                            <form id="logout-form" action="{{ url('/logout') }}" method="POST"
                                                  style="display: none;">
                                                {{ csrf_field() }}
                                            </form>

        @include('layouts.sidebar')

                @yield('content')

                Copyright © 2017 Comdexx Solutions LLC. All rights reserved.

    @else

                    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
                            data-target="#app-navbar-collapse">
                        Toggle Navigation

                    </button>

                        Datacenter Automation Suite

Home

Login

                        @yield('content')

    @endif

@routes

@yield('scripts')


text:
namespace Microsoft.Azure.Synapse.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    public partial class LivyStatementsResponseBody
    {
        /// <summary>
        /// Initializes a new instance of the LivyStatementsResponseBody class.
        /// </summary>
        public LivyStatementsResponseBody()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the LivyStatementsResponseBody class.
        /// </summary>
        public LivyStatementsResponseBody(int? totalStatements = default(int?), IList<LivyStatementResponseBody> statements = default(IList<LivyStatementResponseBody>))
        {
            TotalStatements = totalStatements;
            Statements = statements;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "total_statements")]
        public int? TotalStatements { get; set; }

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "statements")]
        public IList<LivyStatementResponseBody> Statements { get; set; }

    }
}


text:
from django.db import migrations

def create_waffle_switch(apps, schema_editor):
    Switch = apps.get_model('waffle', 'Switch')
    Switch.objects.create(name='return-to-amo-for-all-listed', active=False)

class Migration(migrations.Migration):

    dependencies = [
        ('search', '0001_remove-es-use-classic-similarity-waffle-switch'),
    ]

    operations = [migrations.RunPython(create_waffle_switch)]


text:
{% extends "layout/landing.html" %}
{% block body %}

  {% if error %}

    Error: {{ error }}

  {% endif %}
  <form action="{{ url_for('login') }}" method="post">

<input type="text" name="username" placeholder="username">

<input type="password" name="password" placeholder="password">

Reset Password

        <input type="submit" value="Log In">

  </form>

{% endblock %}


text:
<?php
/**
 * Created by PhpStorm.
 * User: NicolasUffer
 * Date: 20.10.16
 * Time: 20:33
 */

namespace AppBundle\Repository;

use AppBundle\Entity\Payement;

class PayementRepository extends Repository{

    public function findNotValidated(){

        return $this->findBy(array('validated'=>false));

    }

    /**
     *
     * @override
     * @param $payement
     * @throws Exception
     */
    public function remove($payement){

        if($payement instanceof Payement)
        {

            if($payement->isRemovable())
            {
                parent::remove($payement);
            }
            else
                throw new Exception('The payement is linked to a facture');

        }
        else
            throw new Exception('The entity is not an instance of Payement');

    }

}


text:
package com.codnos.dbgp.internal.commands.breakpoint;

import com.codnos.dbgp.api.Breakpoint;
import com.codnos.dbgp.internal.xml.XmlBuilder;
import org.w3c.dom.Node;

import static com.codnos.dbgp.api.Breakpoint.aBreakpoint;
import static com.codnos.dbgp.internal.xml.XmlBuilder.e;
import static com.codnos.dbgp.internal.xml.XmlUtil.optionalIntForXPath;
import static com.codnos.dbgp.internal.xml.XmlUtil.optionalStringForXPath;
import static com.codnos.dbgp.internal.xml.XmlUtil.stringForXPath;

public class BreakpointConverter {
    public static Breakpoint breakpointFromNode(Node breakpointNode) {
        return aBreakpoint()
                .withBreakpointId(stringForXPath(breakpointNode, "@id"))
                .withEnabled(!"disabled".equals(stringForXPath(breakpointNode, "@state")))
                .withTemporary("1".equals(stringForXPath(breakpointNode, "@temporary")))
                .withType(stringForXPath(breakpointNode, "@type"))
                .withFileUri(optionalStringForXPath(breakpointNode, "@filename"))
                .withLineNumber(optionalIntForXPath(breakpointNode, "@lineno"))
                .withFunction(optionalStringForXPath(breakpointNode, "@function"))
                .withException(optionalStringForXPath(breakpointNode, "@exception"))
                .withExpression(optionalStringForXPath(breakpointNode, "dbgp:expression/text()"))
                .withHitValue(optionalStringForXPath(breakpointNode, "@hit_value"))
                .withHitCondition(optionalStringForXPath(breakpointNode, "@hit_condition"))
                .withHitCount(optionalIntForXPath(breakpointNode, "@hit_count"))
                .build();
    }

    public static XmlBuilder breakpointToXml(Breakpoint breakpoint) {
        XmlBuilder breakpointXml = e("breakpoint")
                .a("id", breakpoint.getBreakpointId())
                .a("state", breakpointStateAsString(breakpoint))
                .a("type", breakpoint.getType().asString())
                ;
        switch (breakpoint.getType()) {
            case LINE:
                breakpointXml.a("filename", breakpoint.getFileURL().get()).a("lineno", breakpoint.getLineNumber().get());
                break;
        }
        return breakpointXml;
    }

    public static String breakpointStateAsString(Breakpoint breakpoint) {
        return breakpointStateAsString(breakpoint.isEnabled());
    }

    public static String breakpointStateAsString(boolean enabled) {
        return enabled ? "enabled" : "disabled";
    }

    public static boolean breakpointStateFromString(String state) {
        return "enabled".equals(state);
    }
}


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

    Copyright (C) 2015-2022 Philip Helger (www.helger.com)
    philip[at]helger[dot]com

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

            http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.

-->
<BusinessCard xmlns="http://www.peppol.eu/schema/pd/businesscard/20160112/"><ParticipantIdentifier scheme="iso6523-actorid-upis">9905:leckma-peppol</ParticipantIdentifier><BusinessEntity registrationDate="2016-05-26"><Name>IBM Test</Name><CountryCode>DK</CountryCode><GeographicalInformation>Aarhus</GeographicalInformation><WebsiteURI>http://test.ec-servicecenter.dk</WebsiteURI><Contact><Type>tester</Type><Name>kontakt navn</Name></Contact><AdditionalInformation>extra info</AdditionalInformation></BusinessEntity></BusinessCard>


text:
package de.hub.emffrag.testmodels.testmodel.frag.meta;

import de.hub.emffrag.testmodels.testmodel.TestContainmentIndex;
import de.hub.emffrag.testmodels.testmodel.TestObject;
import de.hub.emffrag.testmodels.testmodel.TestObjectIndex;
import de.hub.emffrag.testmodels.testmodel.TestObjectWithIndexes;

/**
 *
 * The Factory for the model.
 * It provides a create method for each non-abstract class of the model.
 *
 * @see de.hub.emffrag.testmodels.testmodel.frag.meta.TestModelPackage
 * @generated
 */
public interface TestModelFactory extends de.hub.emffrag.testmodels.testmodel.TestModelFactory {
	/**
	 * The singleton instance of the factory.
	 *
	 *
	 * @generated
	 */
	TestModelFactory eINSTANCE = de.hub.emffrag.testmodels.testmodel.frag.impl.TestModelFactoryImpl.init();

	/**
	 * Returns a new object of class 'Test Object'.
	 *
	 *
	 * @return a new object of class 'Test Object'.
	 * @generated
	 */
	TestObject createTestObject();

	/**
	 * Returns a new object of class 'Test Object Index'.
	 *
	 *
	 * @return a new object of class 'Test Object Index'.
	 * @generated
	 */
	TestObjectIndex createTestObjectIndex();

	/**
	 * Returns a new object of class 'Test Containment Index'.
	 *
	 *
	 * @return a new object of class 'Test Containment Index'.
	 * @generated
	 */
	TestContainmentIndex createTestContainmentIndex();

	/**
	 * Returns a new object of class 'Test Object With Indexes'.
	 *
	 *
	 * @return a new object of class 'Test Object With Indexes'.
	 * @generated
	 */
	TestObjectWithIndexes createTestObjectWithIndexes();

	/**
	 * Returns the package supported by this factory.
	 *
	 *
	 * @return the package supported by this factory.
	 * @generated
	 */
	TestModelPackage getTestModelPackage();

} //TestModelFactory