text:
.class Lcom/htc/urlshorten/IsgdParser$1;
.super Ljava/lang/Thread;
.source "IsgdParser.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
    value = Lcom/htc/urlshorten/IsgdParser;->shortenUrl(Ljava/lang/String;Landroid/os/Handler;III)V
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = null
.end annotation

# instance fields
.field final synthetic this$0:Lcom/htc/urlshorten/IsgdParser;

# direct methods
.method constructor <init>(Lcom/htc/urlshorten/IsgdParser;)V
    .locals 0
    .parameter

    .prologue
    .line 50
    iput-object p1, p0, Lcom/htc/urlshorten/IsgdParser$1;->this$0:Lcom/htc/urlshorten/IsgdParser;

    invoke-direct {p0}, Ljava/lang/Thread;-><init>()V

    return-void
.end method

# virtual methods
.method public run()V
    .locals 11

    .prologue
    const/4 v10, 0x0

    .line 53
    new-instance v5, Ljava/lang/StringBuilder;

    invoke-direct {v5}, Ljava/lang/StringBuilder;-><init>()V

    .line 54
    .local v5, sb:Ljava/lang/StringBuilder;
    const-string v7, "http://is.gd/api.php?longurl="

    invoke-virtual {v5, v7}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v7

    invoke-static {}, Lcom/htc/urlshorten/IsgdParser;->access$000()Ljava/lang/String;

    move-result-object v8

    invoke-virtual {v7, v8}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v7

    invoke-virtual {v7}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v6

    .line 57
    .local v6, strQueryUrl:Ljava/lang/String;
    :try_start_0
    new-instance v7, Ljava/net/URL;

    invoke-direct {v7, v6}, Ljava/net/URL;-><init>(Ljava/lang/String;)V

    invoke-virtual {v7}, Ljava/net/URL;->openConnection()Ljava/net/URLConnection;

    move-result-object v0

    .line 58
    .local v0, conn:Ljava/net/URLConnection;
    const/16 v7, 0xfa0

    invoke-virtual {v0, v7}, Ljava/net/URLConnection;->setConnectTimeout(I)V

    .line 59
    new-instance v2, Ljava/io/BufferedReader;

    new-instance v7, Ljava/io/InputStreamReader;

    invoke-virtual {v0}, Ljava/net/URLConnection;->getInputStream()Ljava/io/InputStream;

    move-result-object v8

    invoke-direct {v7, v8}, Ljava/io/InputStreamReader;-><init>(Ljava/io/InputStream;)V

    invoke-direct {v2, v7}, Ljava/io/BufferedReader;-><init>(Ljava/io/Reader;)V

    .line 62
    .local v2, in:Ljava/io/BufferedReader;
    :cond_0
    :goto_0
    invoke-virtual {v2}, Ljava/io/BufferedReader;->readLine()Ljava/lang/String;

    move-result-object v3

    .local v3, inputLine:Ljava/lang/String;
    if-eqz v3, :cond_1

    .line 63
    invoke-virtual {v3}, Ljava/lang/String;->length()I

    move-result v7

    if-lez v7, :cond_0

    .line 64
    iget-object v7, p0, Lcom/htc/urlshorten/IsgdParser$1;->this$0:Lcom/htc/urlshorten/IsgdParser;

    #getter for: Lcom/htc/urlshorten/IsgdParser;->mIsgdInfo:Lcom/htc/urlshorten/IsgdInfo;
    invoke-static {v7}, Lcom/htc/urlshorten/IsgdParser;->access$100(Lcom/htc/urlshorten/IsgdParser;)Lcom/htc/urlshorten/IsgdInfo;

    move-result-object v7

    invoke-virtual {v7, v3}, Lcom/htc/urlshorten/IsgdInfo;->setShortUrl(Ljava/lang/String;)V
    :try_end_0
    .catch Ljava/net/SocketTimeoutException; {:try_start_0 .. :try_end_0} :catch_0
    .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_1

    goto :goto_0

    .line 73
    .end local v0           #conn:Ljava/net/URLConnection;
    .end local v2           #in:Ljava/io/BufferedReader;
    .end local v3           #inputLine:Ljava/lang/String;
    :catch_0
    move-exception v1

    .line 74
    .local v1, e:Ljava/net/SocketTimeoutException;
    const-string v7, "KENLOG"

    new-instance v8, Ljava/lang/StringBuilder;

    invoke-direct {v8}, Ljava/lang/StringBuilder;-><init>()V

    const-string v9, "<IsgdParser.getShorterUrl> e="

    invoke-virtual {v8, v9}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v8

    invoke-virtual {v8, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v8

    invoke-virtual {v8}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v8

    invoke-static {v7, v8}, Landroid/util/Log;->i(Ljava/lang/String;Ljava/lang/String;)I

    .line 75
    invoke-static {}, Landroid/os/Message;->obtain()Landroid/os/Message;

    move-result-object v4

    .line 76
    .local v4, msg:Landroid/os/Message;
    invoke-static {}, Lcom/htc/urlshorten/IsgdParser;->access$500()I

    move-result v7

    iput v7, v4, Landroid/os/Message;->what:I

    .line 77
    iput-object v10, v4, Landroid/os/Message;->obj:Ljava/lang/Object;

    .line 78
    invoke-static {}, Lcom/htc/urlshorten/IsgdParser;->access$400()Landroid/os/Handler;

    move-result-object v7

    invoke-virtual {v7, v4}, Landroid/os/Handler;->sendMessage(Landroid/os/Message;)Z

    .line 86
    .end local v1           #e:Ljava/net/SocketTimeoutException;
    :goto_1
    return-void

    .line 66
    .end local v4           #msg:Landroid/os/Message;
    .restart local v0       #conn:Ljava/net/URLConnection;
    .restart local v2       #in:Ljava/io/BufferedReader;
    .restart local v3       #inputLine:Ljava/lang/String;
    :cond_1
    :try_start_1
    invoke-virtual {v2}, Ljava/io/BufferedReader;->close()V

    .line 68
    invoke-static {}, Landroid/os/Message;->obtain()Landroid/os/Message;

    move-result-object v4

    .line 69
    .restart local v4       #msg:Landroid/os/Message;
    iget-object v7, p0, Lcom/htc/urlshorten/IsgdParser$1;->this$0:Lcom/htc/urlshorten/IsgdParser;

    #getter for: Lcom/htc/urlshorten/IsgdParser;->mIsgdInfo:Lcom/htc/urlshorten/IsgdInfo;
    invoke-static {v7}, Lcom/htc/urlshorten/IsgdParser;->access$100(Lcom/htc/urlshorten/IsgdParser;)Lcom/htc/urlshorten/IsgdInfo;

    move-result-object v7

    invoke-virtual {v7}, Lcom/htc/urlshorten/IsgdInfo;->getShortUrl()Ljava/lang/String;

    move-result-object v7

    if-eqz v7, :cond_2

    iget-object v7, p0, Lcom/htc/urlshorten/IsgdParser$1;->this$0:Lcom/htc/urlshorten/IsgdParser;

    #getter for: Lcom/htc/urlshorten/IsgdParser;->mIsgdInfo:Lcom/htc/urlshorten/IsgdInfo;
    invoke-static {v7}, Lcom/htc/urlshorten/IsgdParser;->access$100(Lcom/htc/urlshorten/IsgdParser;)Lcom/htc/urlshorten/IsgdInfo;

    move-result-object v7

    invoke-virtual {v7}, Lcom/htc/urlshorten/IsgdInfo;->getShortUrl()Ljava/lang/String;

    move-result-object v7

    invoke-virtual {v7}, Ljava/lang/String;->length()I

    move-result v7

    if-lez v7, :cond_2

    invoke-static {}, Lcom/htc/urlshorten/IsgdParser;->access$200()I

    move-result v7

    :goto_2
    iput v7, v4, Landroid/os/Message;->what:I

    .line 70
    iget-object v7, p0, Lcom/htc/urlshorten/IsgdParser$1;->this$0:Lcom/htc/urlshorten/IsgdParser;

    #getter for: Lcom/htc/urlshorten/IsgdParser;->mIsgdInfo:Lcom/htc/urlshorten/IsgdInfo;
    invoke-static {v7}, Lcom/htc/urlshorten/IsgdParser;->access$100(Lcom/htc/urlshorten/IsgdParser;)Lcom/htc/urlshorten/IsgdInfo;

    move-result-object v7

    iput-object v7, v4, Landroid/os/Message;->obj:Ljava/lang/Object;

    .line 71
    invoke-static {}, Lcom/htc/urlshorten/IsgdParser;->access$400()Landroid/os/Handler;

    move-result-object v7

    invoke-virtual {v7, v4}, Landroid/os/Handler;->sendMessage(Landroid/os/Message;)Z
    :try_end_1
    .catch Ljava/net/SocketTimeoutException; {:try_start_1 .. :try_end_1} :catch_0
    .catch Ljava/io/IOException; {:try_start_1 .. :try_end_1} :catch_1

    goto :goto_1

    .line 79
    .end local v0           #conn:Ljava/net/URLConnection;
    .end local v2           #in:Ljava/io/BufferedReader;
    .end local v3           #inputLine:Ljava/lang/String;
    .end local v4           #msg:Landroid/os/Message;
    :catch_1
    move-exception v1

    .line 80
    .local v1, e:Ljava/io/IOException;
    const-string v7, "KENLOG"

    new-instance v8, Ljava/lang/StringBuilder;

    invoke-direct {v8}, Ljava/lang/StringBuilder;-><init>()V

    const-string v9, "<IsgdParser.getShorterUrl> e="

    invoke-virtual {v8, v9}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v8

    invoke-virtual {v8, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v8

    invoke-virtual {v8}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v8

    invoke-static {v7, v8}, Landroid/util/Log;->i(Ljava/lang/String;Ljava/lang/String;)I

    .line 81
    invoke-static {}, Landroid/os/Message;->obtain()Landroid/os/Message;

    move-result-object v4

    .line 82
    .restart local v4       #msg:Landroid/os/Message;
    invoke-static {}, Lcom/htc/urlshorten/IsgdParser;->access$300()I

    move-result v7

    iput v7, v4, Landroid/os/Message;->what:I

    .line 83
    iput-object v10, v4, Landroid/os/Message;->obj:Ljava/lang/Object;

    .line 84
    invoke-static {}, Lcom/htc/urlshorten/IsgdParser;->access$400()Landroid/os/Handler;

    move-result-object v7

    invoke-virtual {v7, v4}, Landroid/os/Handler;->sendMessage(Landroid/os/Message;)Z

    goto :goto_1

    .line 69
    .end local v1           #e:Ljava/io/IOException;
    .restart local v0       #conn:Ljava/net/URLConnection;
    .restart local v2       #in:Ljava/io/BufferedReader;
    .restart local v3       #inputLine:Ljava/lang/String;
    :cond_2
    :try_start_2
    invoke-static {}, Lcom/htc/urlshorten/IsgdParser;->access$300()I
    :try_end_2
    .catch Ljava/net/SocketTimeoutException; {:try_start_2 .. :try_end_2} :catch_0
    .catch Ljava/io/IOException; {:try_start_2 .. :try_end_2} :catch_1

    move-result v7

    goto :goto_2
.end method


text:
import { connect } from "react-redux";
import { updateTags } from "../redux/actions/index.js";

const mapStateToProps = ({ tags, gameplay, gifs, correctAnswers }) => ({
  correctAnswers,
  tags,
  gameplay,
  gifs
});

const mapDispatchToProps = dispatch => {
  return {
    onSortEnd: ({ oldIndex, newIndex }) => {
      dispatch(updateTags(oldIndex, newIndex));
    }
  };
};

const ListInfo = connect(mapStateToProps, mapDispatchToProps);

export default ListInfo;

redpajama_set_name: RedPajamaGithub


text:
package com.antoniotari.audiosister;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;

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

public class NotificationsUtil {

    public static void notification(String title, String message, Context context, Class clazz, int iconRes) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        int notificationId = createID();
        String channelId = "channel-id";
        String channelName = "Channel Name";
        int importance = NotificationManager.IMPORTANCE_HIGH;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(
                    channelId, channelName, importance);
            notificationManager.createNotificationChannel(mChannel);
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
                .setSmallIcon(iconRes)//R.mipmap.ic_launcher
                .setContentTitle(title)
                .setContentText(message)
                .setVibrate(new long[]{100, 250})
                .setLights(Color.GREEN, 500, 5000)
                .setAutoCancel(true);
                //.setColor(ContextCompat.getColor(context, R.color.colorPrimary));

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addNextIntent(new Intent(context, clazz));
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        notificationManager.notify(notificationId, mBuilder.build());
    }

    public static int createID() {
        Date now = new Date();
        int id = Integer.parseInt(new SimpleDateFormat("ddHHmmss", Locale.FRENCH).format(now));
        return id;
    }
}


text:
({
    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Show a message
     **/
    showMessage : function(title, message, type, mode, duration) {
        var showToast = $A.get('e.force:showToast');
        showToast.setParams({
            'title': title,
            'message': message,
            'type': type,
            'mode': mode,
            'duration' : duration
        });
        // Fire the event
        showToast.fire();
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Show a quick info message
     **/
    showQuickMessage : function(type, title, message) {
        this.showMessage(title, message, type, 'dismissible', 2500);
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Show the spinner
     **/
    showSpinner : function(component) {
        var loadingSpinner = component.find('loadingSpinner');
        $A.util.removeClass(loadingSpinner instanceof Array ? loadingSpinner[0] : loadingSpinner, 'slds-hide');
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Hide the spinner
     **/
    hideSpinner : function(component) {
        var loadingSpinner = component.find('loadingSpinner');
        $A.util.addClass(loadingSpinner instanceof Array ? loadingSpinner[0] : loadingSpinner, 'slds-hide');
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Create HTML
     **/
    createHTML : function(component, body, tag, HTMLAttributes, bindComponent) {
        $A.createComponent(
            'aura:html',
            {
                'tag':            tag,
                'body':           body,
                'HTMLAttributes': HTMLAttributes
            },
            function(newComponent, status, errorMessage) {
                // Add the Aura Component to the binding component
                if (status === 'SUCCESS') {
                    bindComponent.push(newComponent);
                }
                else if (status === 'INCOMPLETE') {
                    component.set('v.theError', 'Error: No response from server or client is offline.');
                }
                else if (status === 'ERROR') {
                    component.set('v.theError', 'Error: ' + errorMessage);
                }
            }
        );
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Create a grid block
     **/
    createGrid : function(component, body, bindComponent) {
        this.createHTML(
            component,
            body,
            'div',
            {'class':'slds-grid slds-wrap slds-grid--pull-padded'},
            bindComponent
        );
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Create a column
     **/
    createColumn : function(component, body, bindComponent, columns) {
        // Set sizes
        var mediumSize = 6/columns;
        var largeSize = 12/columns;
        this.createHTML(
            component,
            body,
            'div',
            {'class':'slds-p-horizontal--small slds-size--1-of-1 slds-medium-size--'+mediumSize+'-of-6 slds-large-size--'+largeSize+'-of-12'},
            bindComponent
        );
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Create a select option component
     **/
    createSelectOption : function(component, option, bindComponent) {
        this.createHTML(component, [], 'option', {'value':option.value,'text':option.label}, bindComponent);
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Create an input component per type
     **/
    createInputField : function(component, fieldName, field, bindComponent) {
        // Get the record
        var theRecord = component.get('v.theRecord');
        // Custom field types
        var customInputFieldTypeMap = {
            select          :   'ui:inputSelect',
            textarea        :   'lightning:textarea',
            date            :   'ui:inputDate',
            datetime        :   'ui:inputDateTime',
            richtext        :   'lightning:inputRichText',
            lookup          :   'c:LookupField'
        };
        // If this is a select
        if (field.type == 'select') {
            // For each option
            for (var i = 0; i < field.options.length; i++) {
                // If this should be selected
                if (field.options[i].value == theRecord[fieldName]) {
                    // Set selected
                    field.options[i].selected = 'true';
                }
            }
        }
        // If this is a lookup
        if (field.type == 'lookup') {
            // Add the required attributes
            field['recordId'] = component.get('v.recordId');
            field['editMode'] = true;
        }
        // Create the component
        $A.createComponent(
            field.type in customInputFieldTypeMap ? customInputFieldTypeMap[field.type] : 'lightning:input',
            field,
            function(newComponent, status, errorMessage) {
                // Add the Aura Component to the binding component
                if (status === 'SUCCESS') {
                    // Set the value reference
                    newComponent.set('v.value', component.getReference('v.theRecord.'+fieldName));
                    // Bind
                    bindComponent.push(newComponent);
                }
                else if (status === 'INCOMPLETE') {
                    component.set('v.theError', 'Error: No response from server or client is offline.');
                }
                else if (status === 'ERROR') {
                    component.set('v.theError', 'Error: ' + errorMessage);
                }
            }
        );
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Create an output component per type
     **/
    createOutputUI : function(component, fieldName, field, bindComponent) {
        // Map the different types of output
        var customOutputFieldTypeMap = {
            address         :   'ui:outputText',
            text            :   'ui:outputText',
            checkbox        :   'ui:outputCheckbox',
            date            :   'ui:outputDate',
            datetime        :   'ui:outputDateTime',
            email           :   'ui:outputEmail',
            select          :   'ui:outputText',
            tel             :   'ui:outputPhone',
            textarea        :   'ui:outputTextArea',
            time            :   'ui:outputText',
            currency        :   'ui:outputCurrency',
            richtext        :   'ui:outputRichText',
            lookup          :   'c:LookupField'
        };
        // If we have have a formatter & its currency
        if (field.formatter && field.formatter == 'currency') {
            // Set output as currency
            field.type = 'currency';
        }
        // If this is a lookup
        if (field.type == 'lookup') {
            // Add the required attributes
            field['recordId'] = component.get('v.recordId');
            field['editMode'] = false;
        }
        $A.createComponent(
            field.type in customOutputFieldTypeMap ? customOutputFieldTypeMap[field.type] : 'ui:outputText',
            field,
            function(newComponent, status, errorMessage) {
                // Add the Aura Component to the binding component
                if (status === 'SUCCESS') {
                    // Set the value reference
                    newComponent.set('v.value', component.getReference('v.theRecord.'+fieldName));
                    // Bind
                    bindComponent.push(newComponent);
                }
                else if (status === 'INCOMPLETE') {
                    component.set('v.theError', 'Error: No response from server or client is offline.');
                }
                else if (status === 'ERROR') {
                    component.set('v.theError', 'Error: ' + errorMessage);
                }
            }
        );
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Create an output component
     **/
    createOutputField : function(component, fieldName, field, bindComponent) {
        // Get the record
        var theRecord = component.get('v.theRecord');
        // If we have a value
        if (theRecord[fieldName]) {
            // If this is a url
            if (field.type == 'url') {
                // Create the URL
                var url = theRecord[fieldName];
                var httpString  = 'http://',
                    httpsString = 'https://';
                if (url.substr(0, 1) !== '/' &&
                    url.substr(0, httpString.length) !== httpString &&
                    url.substr(0, httpsString.length) !== httpsString) {
                    url = httpString + url;
                }
                // Create the anchor link
                this.createHTML(
                    component,
                    theRecord[fieldName],
                    'a',
                    {'href':url,'target':'_blank','class':'uiOutputURL slds-truncate','style':'display: inline-block;'},
                    bindComponent
                );
            } else {
                this.createOutputUI(component, fieldName, field, bindComponent);
                // If this is an address (for demo purposes manually show address for streets)
                if (field.type == 'address' || fieldName == 'BillingStreet' || fieldName == 'ShippingStreet') {
                    // Get the encoded address
                    var encodedAddress = encodeURI(theRecord[fieldName]);
                    // Create the URL
                    var url = 'https://www.google.com/maps/place/' + encodedAddress;
                    // Create the image url
                    var imgURL = 'https://maps.googleapis.com/maps/api/staticmap?center=' + encodedAddress + '&zoom=14&scale=false&size=250x125&maptype=roadmap&format=png&visual_refresh=true';
                    // Create the image
                    var theMapImage = [];
                    this.createHTML(
                        component,
                        '',
                        'img',
                        {'src':imgURL,'alt':theRecord[fieldName]},
                        theMapImage
                    );
                    // Create the anchor link
                    this.createHTML(
                        component,
                        theMapImage,
                        'a',
                        {'href':url,'target':'_blank','class':'slds-m-top--medium','style':'display:block;'},
                        bindComponent
                    );
                }
            }
        } else {
            this.createHTML(component, 'No value set', 'span', {'class':'slds-badge'}, bindComponent);
        }
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Create a label
     **/
    createLabel : function(component, fieldName, field, bindComponent) {
        var labelElem = [];
        var labelBody = [];
        // If required
        if (field.required) {
            // Created the required indicator
            this.createHTML(component, '*', 'abbr', {'class':'slds-required','title':field.label+' is a required field'}, labelBody);
        }
        // Add the label text
        this.createHTML(component, field.label, 'span', {'class':'label-span'}, labelBody);
        // Create the label
        this.createHTML(component, labelBody, 'label', {'class':'slds-form-element__label','name':fieldName}, labelElem);
        // Create a container for the label
        this.createHTML(component, labelElem, 'div', {'class':'slds-p-bottom--small'}, bindComponent);
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Create a field output & label or input if not disabled
     **/
    createField : function(component, fieldName, field, bindContainer, columns, fieldIndex) {
        // Clear the container for the field
        var fieldContainer = [];
        // If we are in editMode and the field is editable
        if (component.get('v.editMode') && !field.disabled) {
            // If this is a richtext we need a label
            if (field.type == 'richtext') {
                // Create a label
                this.createLabel(component, fieldName, field, fieldContainer);
            }
            // Create the input
            this.createInputField(component, fieldName, field, fieldContainer);
        } else {
            // Create a label
            this.createLabel(component, fieldName, field, fieldContainer);
            // Create the output
            this.createOutputField(component, fieldName, field, fieldContainer);
        }
        // Create a wrapper for the field container
        var fieldWrapper = [];
        this.createHTML(component, fieldContainer, 'div', {'class':'slds-p-top--small slds-p-bottom--small'+(fieldIndex > columns ? ' slds-border--top' : '')}, fieldWrapper);
        // Create a new column and add the wrapper
        this.createColumn(component, fieldWrapper, bindContainer, columns);
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        4 May 2017
     * @description: Create the field components
     **/
    createFieldComponents : function(component) {
        // Show the spinner
        this.showSpinner(component);
        // Init field container
        var recordDetailView = [];
        // Get the record
        var theRecord = component.get('v.theRecord');
        // Get the fieldsetFields
        var fieldsetFields = component.get('v.fieldsetFields');
        // If we have a record
        if (theRecord) {
            // Get the columns / size
            var columns = component.get('v.columns');
            // Keep track of the field index
            var fieldIndex = 0;
            // For each field
            for (var fieldName in fieldsetFields) {
                // If key exists and the record has the field
                if (fieldsetFields.hasOwnProperty(fieldName) && fieldName in theRecord) {
                    // Increment the field index
                    fieldIndex += 1;
                    // Create a new field
                    this.createField(
                        component,
                        fieldName,
                        fieldsetFields[fieldName],
                        recordDetailView,
                        columns,
                        fieldIndex
                    );
                }
            }
        }
        // Create grid container
        var recordDetailViewGrid = [];
        // Create a grid block for fields
        this.createGrid(component, recordDetailView, recordDetailViewGrid);
        // Set the field grid
        component.set('v.recordDetailView', recordDetailViewGrid);
        // Hide the spinner
        this.hideSpinner(component);
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Get the sObject Label
     **/
    getSObjectLabel : function(component, helper) {
        // Show the spinner
        this.showSpinner(component);
        // Get the sObjectName
        var sObjectName = component.get('v.sObjectName');
        // Setup the server call to get the sobject label
        var getSObjectTypeLabelAction = component.get('c.getSObjectTypeLabel');
        // Store server response if possible
        getSObjectTypeLabelAction.setStorable();
        // Add the Params
        getSObjectTypeLabelAction.setParams({sObjectName : sObjectName});
        // Create a callback that is executed after the server-side action returns
        getSObjectTypeLabelAction.setCallback(this, function(response) {
            // Check the state
            var state = response.getState();
            // If it is successful
            if (component.isValid() && state === 'SUCCESS') {
                // Store the label
                component.set('v.sObjectTypeLabel', response.getReturnValue());
                // Get the labels
                var sObjectLabels = response.getReturnValue();
                // If there is no error
                if (!('error' in sObjectLabels)) {
                    // Store the labels
                    component.set('v.sObjectTypeLabel', sObjectLabels.Label);
                    component.set('v.sObjectTypeLabelPlural', sObjectLabels.LabelPlural);
                } else {
                    // Set the error
                    component.set('v.theError', 'Error Message: ' + sObjectLabels.error);
                }
            } else if (component.isValid() && state === 'ERROR') {
                // Get the errors
                var theError = '';
                var errors = response.getError();
                if (errors) {
                    for (var i = 0; i < errors.length; i++) {
                        if (errors[i] && errors[i].message) {
                            theError += (theError == '' ? '' : ' ') + 'Error message: ' + errors[i].message;
                        }
                    }
                } else {
                    theError = 'Unknown error';
                }
                component.set('v.theError', theError);
            }
            // Hide the spinner
            helper.hideSpinner(component);
        });
        // Add the server action call to the queue
        $A.enqueueAction(getSObjectTypeLabelAction);
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Set the name as the title
     **/
    setNameAsTitle : function(component) {
        // Get the record
        var theRecord = component.get('v.theRecord');
        // Set the new Title
        component.set('v.title', theRecord.Name);
    },

    /**
     * @author:      Tiaan Swart (tiaan@cloudinit.nz)
     * @date:        21 April 2017
     * @description: Get all of the Fields from the fieldset
     **/
    getFieldsetFields : function(component, helper) {
        // Show the spinner
        this.showSpinner(component);
        // Get the sObjectName
        var sObjectName = component.get('v.sObjectName');
        // Get the fieldSetName
        var fieldSetName = component.get('v.fieldSetName');
        // Setup the server call to get the fieldset
        var getFieldsetAction = component.get('c.getFieldset');
        // Store server response if possible
        getFieldsetAction.setStorable();
        // Add the Params
        getFieldsetAction.setParams({sObjectName : sObjectName, fieldSetName : fieldSetName});
        // Create a callback that is executed after the server-side action returns
        getFieldsetAction.setCallback(this, function(response) {
            // Check the state
            var state = response.getState();
            // If it is successful
            if (component.isValid() && state === 'SUCCESS') {
                // Get the fieldset fields
                var fieldsetFields = response.getReturnValue();
                // If there is no error
                if (!('error' in fieldsetFields)) {
                    // Store the fieldset
                    component.set('v.fieldsetFields', fieldsetFields.fieldset);
                    // Get the field names from the fieldset
                    component.set('v.fieldNames', Object.keys(component.get('v.fieldsetFields')));
                    // Find the record
                    var forceRecord = component.find('forceRecord');
                    // Reload the record with the new fields (Will trigger reload and build component)
                    forceRecord.reloadRecord();
                } else {
                    // Set the error
                    component.set('v.theError', 'Error Message: ' + fieldsetFields.error);
                }
            } else if (component.isValid() && state === 'ERROR') {
                // Get the errors
                var theError = '';
                var errors = response.getError();
                if (errors) {
                    for (var i = 0; i < errors.length; i++) {
                        if (errors[i] && errors[i].message) {
                            theError += (theError == '' ? '' : ' ') + 'Error message: ' + errors[i].message;
                        }
                    }
                } else {
                    theError = 'Unknown error';
                }
                component.set('v.theError', theError);
            }
            // Hide the spinner
            helper.hideSpinner(component);
        });
        // Add the server action call to the queue
        $A.enqueueAction(getFieldsetAction);
    }
})


text:
from .. import Command

@Command('/subscribe')
def subscribe_command(*args):
    return 'Sorry, I still have to learn to do that...'

# class SubscribeCommand:
#
#     def __call__(self, *args):
#         return 'Sorry, I still have to learn to do that...'


text:
package flens.input.util;

import flens.core.Flengine;
import flens.core.Record;
import flens.core.Tagger;

import java.util.Map;

public class InputQueueExposer extends AbstractInput {

    private boolean stopped;

    public InputQueueExposer(String name, String plugin, Tagger tagger) {
        super(name, plugin, tagger);
    }

    public void send(Record rec) {
        dispatch(rec);
    }

    @Override
    public void start() {
    }

    @Override
    public void stop() {
        stopped = true;
    }

    @Override
    public void join() throws InterruptedException {
    }

    public boolean isStopped() {
        return stopped;
    }

    @Override
    public void writeConfig(Flengine engine, Map<String, Object> tree) {
    }

}


text:
from PyQt4 import Qt, QtCore, Qt

class OkEditWidgetLabel(Qt.QLabel):
    def __init__(self, text, parent=None, flags=Qt.Qt.Widget):
        Qt.QLabel.__init__(self, text, parent, flags)

    def paintEvent(self, event):
        self.setMinimumSize(200, 40)
        tmpPainter = Qt.QPainter()
        tmpPainter.begin(self)
        #tmpBrush = Qt.QBrush(Qt.QColor(33,  133,  197))
        #tmpPainter.fillRect(QtCore.QRectF(self.rect().left() + 36,  self.rect().top(),  self.rect().width(),
        #        self.rect().height()), tmpBrush)
        #tmpPainter.drawImage(QtCore.QPoint(0, 0), self.image.scaled(35, 35))
        tmpPainter.setFont(Qt.QFont("微软雅黑", 14))
        tmpPainter.setPen(Qt.QColor(255,  255,  255))
        tmpPainter.drawText(QtCore.QRectF(self.rect().left() ,  self.rect().top(),  self.rect().width(),
                self.rect().height()),  Qt.Qt.AlignVCenter, self.text())
        tmpPainter.end()
        event.accept()

class OkTagLabel(Qt.QLabel):
    def __init__(self, text, parent=None, flags=Qt.Qt.Widget):
        Qt.QLabel.__init__(self, text, parent, flags)
        self.setStyleSheet("QLabel{"
                    "height: 25px;"
                    "font-family: '微软雅黑';"
                    "color: #FFFFFF;"
                    "font-size: 15px;"
                    "padding-left: 20px"
                "}")


text:
'use strict';

/**
 * @ngdoc component
 * @name stockTrackAngularJsApp.component:color-number
 * @element color-number
 * @restrict E
 *
 * @description
 * Display the number with a positive or negative class.
 *
 * @param {Number} number Number to test if positive or negative
 */
angular.module('stockTrackAngularJsApp')
  .component('colorNumber', {
      bindings: {
        number: '<'
      },
      templateUrl: 'views/components/color-number.html',
      restrict: 'E'
  });


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Roureopsis confundens Leenh.

### Remarks
null


text:
YUI.add('event-mousewheel', function(Y) {

/**
 * Adds mousewheel event support
 * @module event
 * @submodule event-mousewheel
 */
var DOM_MOUSE_SCROLL = 'DOMMouseScroll',
    fixArgs = function(args) {
        var a = Y.Array(args, 0, true), target;
        if (Y.UA.gecko) {
            a[0] = DOM_MOUSE_SCROLL;
            target = Y.config.win;
        } else {
            target = Y.config.doc;
        }

        if (a.length < 3) {
            a[2] = target;
        } else {
            a.splice(2, 0, target);
        }

        return a;
    };

/**
 * Mousewheel event.  This listener is automatically attached to the
 * correct target, so one should not be supplied.  Mouse wheel
 * direction and velocity is stored in the 'mouseDelta' field.
 * @event mousewheel
 * @param type {string} 'mousewheel'
 * @param fn {function} the callback to execute
 * @param context optional context object
 * @param args 0..n additional arguments to provide to the listener.
 * @return {EventHandle} the detach handle
 * @for YUI
 */
Y.Env.evt.plugins.mousewheel = {
    on: function() {
        return Y.Event._attach(fixArgs(arguments));
    },

    detach: function() {
        return Y.Event.detach.apply(Y.Event, fixArgs(arguments));
    }
};

}, '@VERSION@' ,{requires:['node-base']});


text:
import io
import re

re_indent = re.compile(r'^\ +')

def get_indent(docstr):
    for lstr in map(str.rstrip, docstr.splitlines()):
        indent_match = re_indent.search(lstr)
        if indent_match is not None:
            return indent_match.group()
    return ''

class DocFile(io.StringIO):

    def __init__(self, existing):
        super().__init__()
        super().write(existing)
        self.indent = get_indent(existing)

    def writeline(self, line):
        super().write(self.indent)
        super().write(line)
        super().write('\n')


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="net.ggelardi.uoccin.MainActivity">

    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_action_search"
        android:menuCategory="system"
        android:orderInCategory="1"
        android:title="@string/maiact_act_search"
        app:showAsAction="ifRoom"/>

    <item
        android:id="@+id/action_settings"
        android:menuCategory="system"
        android:orderInCategory="99"
        android:title="@string/action_settings"
        app:showAsAction="never"/>

    <item
        android:id="@+id/action_help"
        android:menuCategory="system"
        android:orderInCategory="100"
        android:title="@string/action_help"
        app:showAsAction="never"/>
</menu>


text:
std::mt19937 UnitRNG::m_gen;

void UnitRNG::init() {
    static std::random_device rd;
    m_gen = std::mt19937{rd()};
}

float UnitRNG::generate() {
    #ifdef BROKEN_STD_GENERATE_CANONICAL
        static const std::uniform_real_distribution<float> dis{0.0, 1.0};
        return dis(m_gen);
    #else
        return std::generate_canonical<float, std::numeric_limits<float>::digits>(gen);
    #endif
}


text:
using content::GpuDataManager;
using content::GpuFeatureType;

namespace {

const char kGpuFeatureNameAccelerated2dCanvas[] = "accelerated_2d_canvas";
const char kGpuFeatureNameAcceleratedCompositing[] = "accelerated_compositing";
const char kGpuFeatureNameWebgl[] = "webgl";
const char kGpuFeatureNameMultisampling[] = "multisampling";
const char kGpuFeatureNameFlash3d[] = "flash_3d";
const char kGpuFeatureNameFlashStage3d[] = "flash_stage3d";
const char kGpuFeatureNameTextureSharing[] = "texture_sharing";
const char kGpuFeatureNameAll[] = "all";
const char kGpuFeatureNameUnknown[] = "unknown";

enum GpuFeatureStatus {
    kGpuFeatureEnabled = 0,
    kGpuFeatureBlacklisted = 1,
    kGpuFeatureDisabled = 2,  // disabled by user but not blacklisted
    kGpuFeatureNumStatus
};

struct GpuFeatureInfo {
  std::string name;
  uint32 blocked;
  bool disabled;
  std::string disabled_description;
  bool fallback_to_software;
};

// Determine if accelerated-2d-canvas is supported, which depends on whether
// lose_context could happen and whether skia is the backend.
bool SupportsAccelerated2dCanvas() {
  if (GpuDataManager::GetInstance()->GetGPUInfo().can_lose_context)
    return false;
#if defined(USE_SKIA)
  return true;
#else
  return false;
#endif
}

DictionaryValue* NewDescriptionValuePair(const std::string& desc,
    const std::string& value) {
  DictionaryValue* dict = new DictionaryValue();
  dict->SetString("description", desc);
  dict->SetString("value", value);
  return dict;
}

DictionaryValue* NewDescriptionValuePair(const std::string& desc,
    Value* value) {
  DictionaryValue* dict = new DictionaryValue();
  dict->SetString("description", desc);
  dict->Set("value", value);
  return dict;
}

Value* NewStatusValue(const char* name, const char* status) {
  DictionaryValue* value = new DictionaryValue();
  value->SetString("name", name);
  value->SetString("status", status);
  return value;
}

std::string GPUDeviceToString(const content::GPUInfo::GPUDevice& gpu) {
  std::string vendor = base::StringPrintf("0x%04x", gpu.vendor_id);
  if (!gpu.vendor_string.empty())
    vendor += " [" + gpu.vendor_string + "]";
  std::string device = base::StringPrintf("0x%04x", gpu.device_id);
  if (!gpu.device_string.empty())
    device += " [" + gpu.device_string + "]";
  return base::StringPrintf(
      "VENDOR = %s, DEVICE= %s", vendor.c_str(), device.c_str());
}

#if defined(OS_WIN)

enum WinSubVersion {
  kWinOthers = 0,
  kWinXP,
  kWinVista,
  kWin7,
  kNumWinSubVersions
};

// Output DxDiagNode tree as nested array of {description,value} pairs
ListValue* DxDiagNodeToList(const content::DxDiagNode& node) {
  ListValue* list = new ListValue();
  for (std::map<std::string, std::string>::const_iterator it =
      node.values.begin();
      it != node.values.end();
      ++it) {
    list->Append(NewDescriptionValuePair(it->first, it->second));
  }

  for (std::map<std::string, content::DxDiagNode>::const_iterator it =
      node.children.begin();
      it != node.children.end();
      ++it) {
    ListValue* sublist = DxDiagNodeToList(it->second);
    list->Append(NewDescriptionValuePair(it->first, sublist));
  }
  return list;
}

int GetGpuBlacklistHistogramValueWin(GpuFeatureStatus status) {
  static WinSubVersion sub_version = kNumWinSubVersions;
  if (sub_version == kNumWinSubVersions) {
    sub_version = kWinOthers;
    std::string version_str = base::SysInfo::OperatingSystemVersion();
    size_t pos = version_str.find_first_not_of("0123456789.");
    if (pos != std::string::npos)
      version_str = version_str.substr(0, pos);
    Version os_version(version_str);
    if (os_version.IsValid() && os_version.components().size() >= 2) {
      const std::vector<uint16>& version_numbers = os_version.components();
      if (version_numbers[0] == 5)
        sub_version = kWinXP;
      else if (version_numbers[0] == 6 && version_numbers[1] == 0)
        sub_version = kWinVista;
      else if (version_numbers[0] == 6 && version_numbers[1] == 1)
        sub_version = kWin7;
    }
  }
  int entry_index = static_cast<int>(sub_version) * kGpuFeatureNumStatus;
  switch (status) {
    case kGpuFeatureEnabled:
      break;
    case kGpuFeatureBlacklisted:
      entry_index++;
      break;
    case kGpuFeatureDisabled:
      entry_index += 2;
      break;
  }
  return entry_index;
}
#endif  // OS_WIN

}  // namespace

namespace gpu_util {

const char kForceCompositingModeFieldTrialName[] = "ForceCompositingMode";
const char kFieldTrialEnabledName[] = "enabled";

void InitializeForceCompositingModeFieldTrial() {
// Enable the field trial only on desktop OS's.
#if !(defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX))
  return;
#endif
  chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
  // Only run the trial on the Canary and Dev channels.
  if (channel != chrome::VersionInfo::CHANNEL_CANARY &&
      channel != chrome::VersionInfo::CHANNEL_DEV)
    return;
#if defined(OS_WIN)
  // Don't run the trial on Windows XP.
  if (base::win::GetVersion() < base::win::VERSION_VISTA)
    return;
#elif defined(OS_MACOSX)
  // Accelerated compositing is only implemented on Mac OSX 10.6 or later.
  if (base::mac::IsOSLeopardOrEarlier())
    return;
#endif

  // Don't activate the field trial if force-compositing-mode has been
  // explicitly disabled from the command line.
  if (CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kDisableForceCompositingMode))
    return;

  const base::FieldTrial::Probability kDivisor = 100;
  scoped_refptr<base::FieldTrial> trial(
    base::FieldTrialList::FactoryGetFieldTrial(
        kForceCompositingModeFieldTrialName, kDivisor,
        "disable", 2012, 12, 31, NULL));

  // Produce the same result on every run of this client.
  trial->UseOneTimeRandomization();
  // 50% probability of being in the enabled group.
  const base::FieldTrial::Probability kEnableProbability = 50;
  int enable_group = trial->AppendGroup(
      kFieldTrialEnabledName, kEnableProbability);

  bool enabled = (trial->group() == enable_group);
  UMA_HISTOGRAM_BOOLEAN("GPU.InForceCompositingModeFieldTrial", enabled);
}

bool InForceCompositingModeTrial() {
  base::FieldTrial* trial =
      base::FieldTrialList::Find(kForceCompositingModeFieldTrialName);
  if (!trial)
    return false;
  return trial->group_name() == kFieldTrialEnabledName;
}

GpuFeatureType StringToGpuFeatureType(const std::string& feature_string) {
  if (feature_string == kGpuFeatureNameAccelerated2dCanvas)
    return content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS;
  else if (feature_string == kGpuFeatureNameAcceleratedCompositing)
    return content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING;
  else if (feature_string == kGpuFeatureNameWebgl)
    return content::GPU_FEATURE_TYPE_WEBGL;
  else if (feature_string == kGpuFeatureNameMultisampling)
    return content::GPU_FEATURE_TYPE_MULTISAMPLING;
  else if (feature_string == kGpuFeatureNameFlash3d)
    return content::GPU_FEATURE_TYPE_FLASH3D;
  else if (feature_string == kGpuFeatureNameFlashStage3d)
    return content::GPU_FEATURE_TYPE_FLASH_STAGE3D;
  else if (feature_string == kGpuFeatureNameTextureSharing)
    return content::GPU_FEATURE_TYPE_TEXTURE_SHARING;
  else if (feature_string == kGpuFeatureNameAll)
    return content::GPU_FEATURE_TYPE_ALL;
  return content::GPU_FEATURE_TYPE_UNKNOWN;
}

std::string GpuFeatureTypeToString(GpuFeatureType type) {
  std::vector<std::string> matches;
  if (type == content::GPU_FEATURE_TYPE_ALL) {
    matches.push_back(kGpuFeatureNameAll);
  } else {
    if (type & content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)
      matches.push_back(kGpuFeatureNameAccelerated2dCanvas);
    if (type & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING)
      matches.push_back(kGpuFeatureNameAcceleratedCompositing);
    if (type & content::GPU_FEATURE_TYPE_WEBGL)
      matches.push_back(kGpuFeatureNameWebgl);
    if (type & content::GPU_FEATURE_TYPE_MULTISAMPLING)
      matches.push_back(kGpuFeatureNameMultisampling);
    if (type & content::GPU_FEATURE_TYPE_FLASH3D)
      matches.push_back(kGpuFeatureNameFlash3d);
    if (type & content::GPU_FEATURE_TYPE_FLASH_STAGE3D)
      matches.push_back(kGpuFeatureNameFlashStage3d);
    if (type & content::GPU_FEATURE_TYPE_TEXTURE_SHARING)
      matches.push_back(kGpuFeatureNameTextureSharing);
    if (!matches.size())
      matches.push_back(kGpuFeatureNameUnknown);
  }
  return JoinString(matches, ',');
}

Value* GetFeatureStatus() {
  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  bool gpu_access_blocked = !GpuDataManager::GetInstance()->GpuAccessAllowed();

  uint32 flags = GpuDataManager::GetInstance()->GetGpuFeatureType();
  DictionaryValue* status = new DictionaryValue();

  const GpuFeatureInfo kGpuFeatureInfo[] = {
      {
          "2d_canvas",
          flags & content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS,
          command_line.HasSwitch(switches::kDisableAccelerated2dCanvas) ||
          !SupportsAccelerated2dCanvas(),
          "Accelerated 2D canvas is unavailable: either disabled at the command"
          " line or not supported by the current system.",
          true
      },
      {
          "compositing",
          flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING,
          command_line.HasSwitch(switches::kDisableAcceleratedCompositing),
          "Accelerated compositing has been disabled, either via about:flags or"
          " command line. This adversely affects performance of all hardware"
          " accelerated features.",
          true
      },
      {
          "3d_css",
          flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING,
          command_line.HasSwitch(switches::kDisableAcceleratedLayers),
          "Accelerated layers have been disabled at the command line.",
          false
      },
      {
          "css_animation",
          flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING,
          command_line.HasSwitch(switches::kDisableThreadedAnimation) ||
          command_line.HasSwitch(switches::kDisableAcceleratedCompositing),
          "Accelerated CSS animation has been disabled at the command line.",
          true
      },
      {
          "webgl",
          flags & content::GPU_FEATURE_TYPE_WEBGL,
          command_line.HasSwitch(switches::kDisableExperimentalWebGL),
          "WebGL has been disabled, either via about:flags or command line.",
          false
      },
      {
          "multisampling",
          flags & content::GPU_FEATURE_TYPE_MULTISAMPLING,
          command_line.HasSwitch(switches::kDisableGLMultisampling),
          "Multisampling has been disabled, either via about:flags or command"
          " line.",
          false
      },
      {
          "flash_3d",
          flags & content::GPU_FEATURE_TYPE_FLASH3D,
          command_line.HasSwitch(switches::kDisableFlash3d),
          "Using 3d in flash has been disabled, either via about:flags or"
          " command line.",
          false
      },
      {
          "flash_stage3d",
          flags & content::GPU_FEATURE_TYPE_FLASH_STAGE3D,
          command_line.HasSwitch(switches::kDisableFlashStage3d),
          "Using Stage3d in Flash has been disabled, either via about:flags or"
          " command line.",
          false
      },
      {
          "texture_sharing",
          flags & content::GPU_FEATURE_TYPE_TEXTURE_SHARING,
          command_line.HasSwitch(switches::kDisableImageTransportSurface),
          "Sharing textures between processes has been disabled, either via"
          " about:flags or command line.",
          false
      }
  };
  const size_t kNumFeatures = sizeof(kGpuFeatureInfo) / sizeof(GpuFeatureInfo);

  // Build the feature_status field.
  {
    ListValue* feature_status_list = new ListValue();

    for (size_t i = 0; i < kNumFeatures; ++i) {
      std::string status;
      if (kGpuFeatureInfo[i].disabled) {
        status = "disabled";
        if (kGpuFeatureInfo[i].name == "css_animation") {
          status += "_software_animated";
        } else {
          if (kGpuFeatureInfo[i].fallback_to_software)
            status += "_software";
          else
            status += "_off";
        }
      } else if (GpuDataManager::GetInstance()->ShouldUseSoftwareRendering()) {
        status = "unavailable_software";
      } else if (kGpuFeatureInfo[i].blocked ||
                 gpu_access_blocked) {
        status = "unavailable";
        if (kGpuFeatureInfo[i].fallback_to_software)
          status += "_software";
        else
          status += "_off";
      } else {
        status = "enabled";
        if (kGpuFeatureInfo[i].name == "webgl" &&
            (command_line.HasSwitch(switches::kDisableAcceleratedCompositing) ||
             (flags & content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING)))
          status += "_readback";
        bool has_thread =
            command_line.HasSwitch(switches::kEnableThreadedCompositing) &&
            !command_line.HasSwitch(switches::kDisableThreadedCompositing);
        if (kGpuFeatureInfo[i].name == "compositing") {
          bool force_compositing =
              (command_line.HasSwitch(switches::kForceCompositingMode) &&
               !command_line.HasSwitch(
                   switches::kDisableForceCompositingMode)) ||
              InForceCompositingModeTrial();
          if (force_compositing)
            status += "_force";
          if (has_thread)
            status += "_threaded";
        }
        if (kGpuFeatureInfo[i].name == "css_animation") {
          if (has_thread)
            status = "accelerated_threaded";
          else
            status = "accelerated";
        }
      }
      feature_status_list->Append(
          NewStatusValue(kGpuFeatureInfo[i].name.c_str(), status.c_str()));
    }

    status->Set("featureStatus", feature_status_list);
  }

  // Build the problems list.
  {
    ListValue* problem_list = new ListValue();

    if (gpu_access_blocked) {
      DictionaryValue* problem = new DictionaryValue();
      problem->SetString("description",
          "GPU process was unable to boot. Access to GPU disallowed.");
      problem->Set("crBugs", new ListValue());
      problem->Set("webkitBugs", new ListValue());
      problem_list->Append(problem);
    }

    for (size_t i = 0; i < kNumFeatures; ++i) {
      if (kGpuFeatureInfo[i].disabled) {
        DictionaryValue* problem = new DictionaryValue();
        problem->SetString(
            "description", kGpuFeatureInfo[i].disabled_description);
        problem->Set("crBugs", new ListValue());
        problem->Set("webkitBugs", new ListValue());
        problem_list->Append(problem);
      }
    }

    GpuBlacklist::GetInstance()->GetBlacklistReasons(problem_list);

    status->Set("problems", problem_list);
  }

  return status;
}

DictionaryValue* GpuInfoAsDictionaryValue() {
  content::GPUInfo gpu_info = GpuDataManager::GetInstance()->GetGPUInfo();
  ListValue* basic_info = new ListValue();
  basic_info->Append(NewDescriptionValuePair(
      "Initialization time",
      base::Int64ToString(gpu_info.initialization_time.InMilliseconds())));
  basic_info->Append(NewDescriptionValuePair(
      "GPU0", GPUDeviceToString(gpu_info.gpu)));
  for (size_t i = 0; i < gpu_info.secondary_gpus.size(); ++i) {
    basic_info->Append(NewDescriptionValuePair(
        base::StringPrintf("GPU%d", static_cast<int>(i + 1)),
        GPUDeviceToString(gpu_info.secondary_gpus[i])));
  }
  basic_info->Append(NewDescriptionValuePair(
      "Optimus", Value::CreateBooleanValue(gpu_info.optimus)));
  basic_info->Append(NewDescriptionValuePair(
      "AMD switchable", Value::CreateBooleanValue(gpu_info.amd_switchable)));
  basic_info->Append(NewDescriptionValuePair("Driver vendor",
                                             gpu_info.driver_vendor));
  basic_info->Append(NewDescriptionValuePair("Driver version",
                                             gpu_info.driver_version));
  basic_info->Append(NewDescriptionValuePair("Driver date",
                                             gpu_info.driver_date));
  basic_info->Append(NewDescriptionValuePair("Pixel shader version",
                                             gpu_info.pixel_shader_version));
  basic_info->Append(NewDescriptionValuePair("Vertex shader version",
                                             gpu_info.vertex_shader_version));
  basic_info->Append(NewDescriptionValuePair("GL version",
                                             gpu_info.gl_version));
  basic_info->Append(NewDescriptionValuePair("GL_VENDOR",
                                             gpu_info.gl_vendor));
  basic_info->Append(NewDescriptionValuePair("GL_RENDERER",
                                             gpu_info.gl_renderer));
  basic_info->Append(NewDescriptionValuePair("GL_VERSION",
                                             gpu_info.gl_version_string));
  basic_info->Append(NewDescriptionValuePair("GL_EXTENSIONS",
                                             gpu_info.gl_extensions));

  DictionaryValue* info = new DictionaryValue();
  info->Set("basic_info", basic_info);

#if defined(OS_WIN)
  ListValue* perf_info = new ListValue();
  perf_info->Append(NewDescriptionValuePair(
      "Graphics",
      base::StringPrintf("%.1f", gpu_info.performance_stats.graphics)));
  perf_info->Append(NewDescriptionValuePair(
      "Gaming",
      base::StringPrintf("%.1f", gpu_info.performance_stats.gaming)));
  perf_info->Append(NewDescriptionValuePair(
      "Overall",
      base::StringPrintf("%.1f", gpu_info.performance_stats.overall)));
  info->Set("performance_info", perf_info);

  Value* dx_info;
  if (gpu_info.dx_diagnostics.children.size())
    dx_info = DxDiagNodeToList(gpu_info.dx_diagnostics);
  else
    dx_info = Value::CreateNullValue();
  info->Set("diagnostics", dx_info);
#endif

  return info;
}

void UpdateStats() {
  GpuBlacklist* blacklist = GpuBlacklist::GetInstance();
  uint32 max_entry_id = blacklist->max_entry_id();
  if (max_entry_id == 0) {
    // GPU Blacklist was not loaded.  No need to go further.
    return;
  }

  const CommandLine& command_line = *CommandLine::ForCurrentProcess();
  uint32 flags = GpuDataManager::GetInstance()->GetGpuFeatureType();
  bool disabled = false;
  if (flags == 0) {
    UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
        0, max_entry_id + 1);
  } else {
    std::vector<uint32> flag_entries;
    blacklist->GetGpuFeatureTypeEntries(
        content::GPU_FEATURE_TYPE_ALL, flag_entries, disabled);
    DCHECK_GT(flag_entries.size(), 0u);
    for (size_t i = 0; i < flag_entries.size(); ++i) {
      UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry",
          flag_entries[i], max_entry_id + 1);
    }
  }

  // This counts how many users are affected by a disabled entry - this allows
  // us to understand the impact of an entry before enable it.
  std::vector<uint32> flag_disabled_entries;
  disabled = true;
  blacklist->GetGpuFeatureTypeEntries(
      content::GPU_FEATURE_TYPE_ALL, flag_disabled_entries, disabled);
  for (size_t i = 0; i < flag_disabled_entries.size(); ++i) {
    UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerDisabledEntry",
        flag_disabled_entries[i], max_entry_id + 1);
  }

  const content::GpuFeatureType kGpuFeatures[] = {
      content::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS,
      content::GPU_FEATURE_TYPE_ACCELERATED_COMPOSITING,
      content::GPU_FEATURE_TYPE_WEBGL
  };
  const std::string kGpuBlacklistFeatureHistogramNames[] = {
      "GPU.BlacklistFeatureTestResults.Accelerated2dCanvas",
      "GPU.BlacklistFeatureTestResults.AcceleratedCompositing",
      "GPU.BlacklistFeatureTestResults.Webgl"
  };
  const bool kGpuFeatureUserFlags[] = {
      command_line.HasSwitch(switches::kDisableAccelerated2dCanvas),
      command_line.HasSwitch(switches::kDisableAcceleratedCompositing),
      command_line.HasSwitch(switches::kDisableExperimentalWebGL)
  };
#if defined(OS_WIN)
  const std::string kGpuBlacklistFeatureHistogramNamesWin[] = {
      "GPU.BlacklistFeatureTestResultsWindows.Accelerated2dCanvas",
      "GPU.BlacklistFeatureTestResultsWindows.AcceleratedCompositing",
      "GPU.BlacklistFeatureTestResultsWindows.Webgl"
  };
#endif
  const size_t kNumFeatures =
      sizeof(kGpuFeatures) / sizeof(content::GpuFeatureType);
  for (size_t i = 0; i < kNumFeatures; ++i) {
    // We can't use UMA_HISTOGRAM_ENUMERATION here because the same name is
    // expected if the macro is used within a loop.
    GpuFeatureStatus value = kGpuFeatureEnabled;
    if (flags & kGpuFeatures[i])
      value = kGpuFeatureBlacklisted;
    else if (kGpuFeatureUserFlags[i])
      value = kGpuFeatureDisabled;
    base::Histogram* histogram_pointer = base::LinearHistogram::FactoryGet(
        kGpuBlacklistFeatureHistogramNames[i],
        1, kGpuFeatureNumStatus, kGpuFeatureNumStatus + 1,
        base::Histogram::kUmaTargetedHistogramFlag);
    histogram_pointer->Add(value);
#if defined(OS_WIN)
    histogram_pointer = base::LinearHistogram::FactoryGet(
        kGpuBlacklistFeatureHistogramNamesWin[i],
        1, kNumWinSubVersions * kGpuFeatureNumStatus,
        kNumWinSubVersions * kGpuFeatureNumStatus + 1,
        base::Histogram::kUmaTargetedHistogramFlag);
    histogram_pointer->Add(GetGpuBlacklistHistogramValueWin(value));
#endif
  }
}

}  // namespace gpu_util;


text:
package CXGN::Trial::TrialDesign::Plugin::Westcott;

use Moose::Role;
use List::Util qw | max |;

sub create_design {
    my $self = shift;
    my %westcott_design;
    my $rbase = R::YapRI::Base->new();
    my @stock_list;
    my $stock_data_matrix;
    my @control_list;
    my %control_names_lookup;
    my $r_block;
    my $result_matrix;
    my @plot_numbers;
    my @stock_names;
    my @block_numbers;
    my @converted_plot_numbers;
    my $westcott_col;
    my $westcott_check_2;
    my $westcott_check_1;
    my $westcott_col_between_check;

    if ($self->has_stock_list()) {
      @stock_list = @{$self->get_stock_list()};
    } else {
      die "No stock list specified\n";
    }
    if ($self->has_control_list_crbd()) {
      @control_list = @{$self->get_control_list_crbd()};
      %control_names_lookup = map { $_ => 1 } @control_list;
      $self->_check_controls_and_accessions_lists;
    }
    if ($self->has_westcott_col()) {
      $westcott_col = $self->get_westcott_col();
    }
    if ($self->has_westcott_check_2()) {
      $westcott_check_2 = $self->get_westcott_check_2();
    }
    if ($self->has_westcott_check_1()) {
      $westcott_check_1 = $self->get_westcott_check_1();
    }
    if ($self->has_westcott_col_between_check()) {
      $westcott_col_between_check = $self->get_westcott_col_between_check();
    }

    $stock_data_matrix =  R::YapRI::Data::Matrix->new({
        name => 'stock_data_matrix',
        rown => 1,
        coln => scalar(@stock_list),
        data => \@stock_list,
    });

    $r_block = $rbase->create_block('r_block');
    $stock_data_matrix->send_rbase($rbase, 'r_block');
    $r_block->add_command('library(devtools)');
    $r_block->add_command('library(st4gi)');
    $r_block->add_command('geno <-  stock_data_matrix[1,]');
    $r_block->add_command('ch1 <- "'.$westcott_check_1.'"');
    $r_block->add_command('ch2 <- "'.$westcott_check_2.'"');
    $r_block->add_command('nc <- '.$westcott_col);
    if ($westcott_col_between_check){
        $r_block->add_command('ncb <- '.$westcott_col_between_check);
        $r_block->add_command('westcott<-cr.w(geno, ch1, ch2, nc, ncb=ncb)');
    }
    else{
        $r_block->add_command('westcott<-cr.w(geno, ch1, ch2, nc)');
    }
    $r_block->add_command('westcott<-westcott$book');
    $r_block->add_command('westcott<-as.matrix(westcott)');
    $r_block->run_block();
    $result_matrix = R::YapRI::Data::Matrix->read_rbase( $rbase,'r_block','westcott');
    @plot_numbers = $result_matrix->get_column("plot.num");
    @stock_names = $result_matrix->get_column("geno");

    my @vector_trt = (1..scalar(@stock_list));
    my %accName;
    for (my $i=0; $i< scalar(@stock_list); $i++){
        $accName{$vector_trt[$i]} = $stock_list[$i];
    }
    for (my $i=0; $i<scalar(@stock_names); $i++){
        for my $trt (keys %accName){
            if ($stock_names[$i] eq $trt){
                $stock_names[$i] = $accName{$trt};
            }
        }
    }

    my @row_numbers = $result_matrix->get_column("row");
    my @col_numbers = $result_matrix->get_column("col");
    @block_numbers = $result_matrix->get_column("row");
    my $max_block = max( @block_numbers );
    @converted_plot_numbers=@{$self->_convert_plot_numbers(\@plot_numbers, \@block_numbers, $max_block)};

    for (my $i = 0; $i < scalar(@converted_plot_numbers); $i++) {
      my %plot_info;
      $plot_info{'is_a_control'} = exists($control_names_lookup{$stock_names[$i]});
      $plot_info{'stock_name'} = $stock_names[$i];
      $plot_info{'block_number'} = $block_numbers[$i];
      $plot_info{'plot_name'} = $converted_plot_numbers[$i];
      $plot_info{'row_number'} = $row_numbers[$i];
      $plot_info{'col_number'} = $col_numbers[$i];
      $plot_info{'plot_number'} = $converted_plot_numbers[$i];
      $plot_info{'plot_num_per_block'} = $converted_plot_numbers[$i];

      $westcott_design{$converted_plot_numbers[$i]} = \%plot_info;
    }
    %westcott_design = %{$self->_build_plot_names(\%westcott_design)};
    return \%westcott_design;
}

1;


text:
<?php

namespace Drest\Event;

use Doctrine\Common\EventSubscriber;

abstract class Subscriber implements EventSubscriber
{
}


text:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

import { AccountService } from 'app/core';
import { PasswordService } from './password.service';

@Component({
  selector: 'dbt-password',
  templateUrl: './password.component.html'
})
export class PasswordComponent implements OnInit {
  doNotMatch: string;
  error: string;
  success: string;
  account: any;
  passwordForm = this.fb.group({
    currentPassword: ['', [Validators.required]],
    newPassword: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(50)]],
    confirmPassword: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(50)]]
  });

  constructor(private passwordService: PasswordService, private accountService: AccountService, private fb: FormBuilder) {}

  ngOnInit() {
    this.accountService.identity().then(account => {
      this.account = account;
    });
  }

  changePassword() {
    const newPassword = this.passwordForm.get(['newPassword']).value;
    if (newPassword !== this.passwordForm.get(['confirmPassword']).value) {
      this.error = null;
      this.success = null;
      this.doNotMatch = 'ERROR';
    } else {
      this.doNotMatch = null;
      this.passwordService.save(newPassword, this.passwordForm.get(['currentPassword']).value).subscribe(
        () => {
          this.error = null;
          this.success = 'OK';
        },
        () => {
          this.success = null;
          this.error = 'ERROR';
        }
      );
    }
  }
}


text:
<?php

/**
 * @package JooS
 * @subpackage Helper
 */
namespace JooS\Helper;

/**
 * Exception.
 */
class Exception extends \Exception
{

}


text:
- $DCOS_CLI_HOME: DCOS command line tool directory
- $MASTER_IP_ADDRESS: Mesos Master IP address
- $PUBLIC_SLAVE_IP_ADDRESS: Mesos Public Slave IP address

## Step 1: base deployment of cAdvisor
Source: https://github.com/google/cadvisor

Deploy the app in Marathon:

    $ dcos marathon app add marathon-cadvisor.json
    $ dcos marathon app list
    ID          MEM   CPUS  TASKS  HEALTH  DEPLOYMENT  CONTAINER  CMD
    /cadvisor  512.0  0.5    1/1    ---       ---        DOCKER   None

Where does it run?

    $ dcos marathon app show cadvisor | grep -w tasks -A 8
    "tasks": [
      {
        "appId": "/cadvisor",
        "host": "ip-10-0-7-124.us-west-2.compute.internal",
        "id": "cadvisor.550f490d-5ba3-11e5-98ec-6ec316fc94b6",
        "ports": [
          12235
        ],

Note the port (`12235`) and point the browser there (`$PUBLIC_SLAVE_IP_ADDRESS:12235/containers/`):

![cAdvisor screenshot](cadvisor-screenshot.png)

## Step 2:  InfluxDB

Deploy InfluxDB in Marathon:

    $ dcos marathon app add marathon-influxdb.json

Where does it run?

    $ dcos marathon app show influxdb | grep -w tasks -A 8
    "tasks": [
      {
        "appId": "/influxdb",
        "host": "ip-10-0-7-124.us-west-2.compute.internal",
        "id": "influxdb.3bb5669e-5baa-11e5-98ec-6ec316fc94b6",
        "ports": [
          20316,
          20317
        ],

Note the first port (`20316`) and point the browser there (`$PUBLIC_SLAVE_IP_ADDRESS:20316`):

![InfluxDB setup screenshot](influxdb-screenshot_0.png)

Last step to set up InfluxDB is to change the port to the second port (`20317`).

Create a database called `test` and use the `Write Data` link (in the WebUI) to create some data:

        testts,tag0=ATAG v=1
        testts,tag0=ATAG v=5
        testts,tag0=ATAG v=7
        testts,tag0=ATAG v=0

Then you can query it like so:

        SELECT * FROM testts

![InfluxDB query screenshot](influxdb-screenshot_1.png)

Last step is to create an administrator user with `admin`|`admin`. See also the [InfluxDB guide](https://influxdb.com/docs/v0.9/introduction/overview.html).

## Step 3: Grafana

Deploy Grafana in Marathon:

    $ dcos marathon app add marathon-grafana.json
    $ dcos marathon app show grafana | grep -w tasks -A 8
    "tasks": [
    {
      "appId": "/grafana",
      "host": "ip-10-0-7-124.us-west-2.compute.internal",
      "id": "grafana.c393d2af-5bae-11e5-98ec-6ec316fc94b6",
      "ports": [
        21403
      ],

And again, following the same steps as above we discover Grafana running on `$PUBLIC_SLAVE_IP_ADDRESS:21403` (log in with `admin`|`admin`)

![Grafana setup screenshot](grafana-screenshot_0.png)

Connect InfluxDB to Grafana:

Note: use the second InfluxDB port (in my case `20317`) to configure the datasource. After you've added a dashboard (which I called `cAdvisor`) and a row (using the `test` database from the data source and selected the `testts` measurement) you should see something like this:

![Grafana test DB/testts measurement plot screenshot](grafana-screenshot_1.png)

See also the [Grafana-InfluxDB setup](http://docs.grafana.org/datasources/influxdb/).

## Step 4: Putting it all together

1. First deploy `marathon-influxdb.json`
1. `CREATE DATABASE ca` and `ALTER RETENTION POLICY default ON ca DURATION 1d`
1. Update `storage_driver_host` args in `marathon-cadvisor-influxdb.json` with the second port (API port) of InfluxDB from step 1.
1. Deploy `marathon-cadvisor-influxdb.json`
1. Deploy and config `marathon-grafana.json`


text:
package com.ibessonov.game.core.common.util;

/**
 * @author ibessonov
 */
@FunctionalInterface
public interface BiIntPredicate {

    boolean test(int a, int b);
}


text:
(function() { 'use strict';

    var BT = (function () {
        function BT(data) {
            this.data = data;
        }

        BT.prototype = {
            constructor: BT,

            iterativeInOrderTraversal: function () {
                var nodes = [],
                    stack = [],
                    currentNode = this.data[0];
                while (currentNode !== undefined || stack.length > 0) {
                    while (currentNode !== undefined) {
                        stack.push(currentNode);
                        currentNode = this.data[currentNode[1]];
                    }
                    if (stack.length > 0) {
                        var topNode = stack.pop();
                        nodes.push(topNode[0]);
                        currentNode = this.data[topNode[2]];
                    }
                }
                return nodes;
            },

            iterativePreOrderTraversal: function () {
                var nodes = [],
                    stack = [],
                    currentNode = this.data[0];
                stack.push(currentNode);
                while (stack.length > 0) {
                    currentNode = stack.pop();
                    nodes.push(currentNode[0]);
                    if (this.data[currentNode[2]] !== undefined) {
                        stack.push(this.data[currentNode[2]]);
                    }
                    if (this.data[currentNode[1]] !== undefined) {
                        stack.push(this.data[currentNode[1]]);
                    }
                }
                return nodes;
            },

            iterativePostOrderTraversal: function () {
                var nodes = [],
                    stack = [],
                    currentNode = this.data[0];
                stack.push(currentNode);
                while (stack.length > 0) {
                    currentNode = stack.pop();
                    nodes.push(currentNode[0]);
                    if (this.data[currentNode[1]] !== undefined) {
                        stack.push(this.data[currentNode[1]]);
                    }
                    if (this.data[currentNode[2]] !== undefined) {
                        stack.push(this.data[currentNode[2]]);
                    }
                }
                return nodes.reverse();
            }
        };

        return BT;
    })();

    ////////////////////////////////

    var fs = require('fs');
    var input = (process.argv.length === 3) ? process.argv[2] : '/dev/stdin';

    var data = fs.readFileSync(input, 'utf8');
    var lines = data.match(/[^\r\n]+/g);

    lines.shift();
    data = lines.map(function (line) {
        return line.split(' ').map(function (number) {
            return parseInt(number);
        });
    });

    var bt = new BT(data);
    console.log(bt.iterativeInOrderTraversal().join(' '));
    console.log(bt.iterativePreOrderTraversal().join(' '));
    console.log(bt.iterativePostOrderTraversal().join(' '));

})();


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

namespace Stolt\GitUserBend\Git;

use Stolt\GitUserBend\Persona;

class User
{
    const REPOSITORY_USER_ALIAS = 'RU';

    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $email;

    /**
     * @var string
     */
    private $alias;

    /**
     * @param string $name
     * @param string $email
     * @param string $alias
     */
    public function __construct(
        $name = null,
        $email = null,
        string $alias = User::REPOSITORY_USER_ALIAS
    ) {
        $this->name = $name;
        $this->email = $email;
        $this->alias = $alias;
    }

    /**
     * @return boolean
     */
    public function hasName(): bool
    {
        return $this->name !== null;
    }

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @param  string $name
     * @return void
     */
    public function setName(string $name)
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getEmail(): string
    {
        return $this->email;
    }

    /**
     * @param  string $email
     * @return void
     */
    public function setEmail(string $email)
    {
        $this->email = $email;
    }

    /**
     * @return boolean
     */
    public function hasEmail(): bool
    {
        return $this->email !== null;
    }

    /**
     * @return string
     */
    public function getAlias(): string
    {
        return $this->alias;
    }

    /**
     * @return boolean
     */
    public function hasAlias(): bool
    {
        return $this->alias !== null;
    }

    /**
     * @return boolean
     */
    public function partial(): bool
    {
        if ($this->hasName() && $this->hasEmail()) {
            return false;
        }

        return true;
    }

    /**
     * @return Stolt\GitUserBend\Persona
     * @throws Stolt\GitUserBend\Exceptions\InvalidPersona
     */
    public function factorPersona(): Persona
    {
        return new Persona(
            $this->getAlias(),
            $this->getName(),
            $this->getEmail()
        );
    }
}


text:
package org.teavm.metaprogramming.test;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
    String a() default "!";

    int b() default 23;

    Class<?>[] c();
}


text:
public class Constants {
    static Token OPEN_PAR = new Token("op_par");
    static Token CLOSE_PAR = new Token("cl_par");
    static Token IF = new Token("if");
    static Token THEN = new Token("then");
    static Token EQUALS = new Token("=");
}


text:
function s1(map, position1, position2){

	  var directionsDisplay;
	  var directionsService = new google.maps.DirectionsService();

	  directionsDisplay = new google.maps.DirectionsRenderer();
	  directionsDisplay.setMap(map);

	/**
	Beispiel: route berechnen - mit optionalen waypoints wird die Route über die angegebenen Stationen berechnet
	*/

	 	var request = {
	    origin:position1,
	    destination:position2,

	    travelMode: google.maps.TravelMode.DRIVING
	  };
	  directionsService.route(request, function(result, status) {
	    if (status == google.maps.DirectionsStatus.OK) {
	      console.log("route. " +result);
	      directionsDisplay.setDirections(result);
	    }else{

	       console.log("route failed. status:" +status +" result:" +result);
	    }
	  });
}

	function initialize() {
		  var mapOptions = {
				  center: new google.maps.LatLng(47.66, 9.16), zoom: 14,
				  mapTypeId: google.maps.MapTypeId.ROADMAP
		  };
		  var map = new google.maps.Map(document.getElementById("map-canvas"),
		  mapOptions);

		  var position2 = new google.maps.LatLng(47.659598,9.177358);
		 var position1 = new google.maps.LatLng( 47.667431,9.171929);
		s1(map,position1,position2 );

	}
	google.maps.event.addDomListener(window, 'load', initialize());


text:
var generateRealPin = function() {
	var pin = "";
	for (var i = 0; i < 6; i++) {
		pin += Math.floor(Math.random() * 10)
	}
	return pin;
};

var generateTestPin = function() {
	return '123456';
};

var generatePin = function() {
	return config.fakePins ? generateTestPin() : generateRealPin();
};

module.exports = {
	generatePin: generatePin
};


text:
package org.wso2.carbon.siddhi.apps.api.rest;

import org.osgi.framework.BundleContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wso2.carbon.uiserver.api.App;
import org.wso2.carbon.uiserver.spi.RestApiProvider;
import org.wso2.msf4j.Microservice;
import java.util.HashMap;
import java.util.Map;

/**
 * Provider that supplies Microservices for the {@link #DASHBOARD_PORTAL_APP_NAME} web app.
 */
@Component(service = RestApiProvider.class,
        immediate = true)
public class SiddhiAppsApiProvider implements RestApiProvider {
    private static final String DASHBOARD_PORTAL_APP_NAME = "analytics-dashboard";
    private static final Logger LOGGER = LoggerFactory.getLogger(SiddhiAppsApiProvider.class);

    @Activate
    protected void activate(BundleContext bundleContext) {
        LOGGER.debug("{} activated.", this.getClass().getName());
    }

    @Deactivate
    protected void deactivate(BundleContext bundleContext) {
        LOGGER.debug("{} deactivated.", this.getClass().getName());
    }

    @Override
    public String getAppName() {
        return DASHBOARD_PORTAL_APP_NAME;
    }

    @Override
    public Map<String, Microservice> getMicroservices(App app) {
        Map<String, Microservice> microservices = new HashMap<>();
        microservices.put(SiddhiAppsApi.API_CONTEXT_PATH, new SiddhiAppsApi());
        return microservices;
    }
}


text:
"""Support for the Transmission BitTorrent client API."""
from datetime import timedelta
import logging

import transmissionrpc
from transmissionrpc.error import TransmissionError
import voluptuous as vol

from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import (
    CONF_HOST,
    CONF_NAME,
    CONF_PASSWORD,
    CONF_PORT,
    CONF_SCAN_INTERVAL,
    CONF_USERNAME,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.util import slugify

from .const import (
    ATTR_TORRENT,
    DEFAULT_NAME,
    DEFAULT_PORT,
    DEFAULT_SCAN_INTERVAL,
    DOMAIN,
    SERVICE_ADD_TORRENT,
)
from .errors import AuthenticationError, CannotConnect, UnknownError

_LOGGER = logging.getLogger(__name__)

SERVICE_ADD_TORRENT_SCHEMA = vol.Schema({vol.Required(ATTR_TORRENT): cv.string})

TRANS_SCHEMA = vol.All(
    vol.Schema(
        {
            vol.Required(CONF_HOST): cv.string,
            vol.Optional(CONF_PASSWORD): cv.string,
            vol.Optional(CONF_USERNAME): cv.string,
            vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
            vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
            vol.Optional(
                CONF_SCAN_INTERVAL, default=DEFAULT_SCAN_INTERVAL
            ): cv.time_period,
        }
    )
)

CONFIG_SCHEMA = vol.Schema(
    {DOMAIN: vol.All(cv.ensure_list, [TRANS_SCHEMA])}, extra=vol.ALLOW_EXTRA
)

async def async_setup(hass, config):
    """Import the Transmission Component from config."""
    if DOMAIN in config:
        for entry in config[DOMAIN]:
            hass.async_create_task(
                hass.config_entries.flow.async_init(
                    DOMAIN, context={"source": SOURCE_IMPORT}, data=entry
                )
            )

    return True

async def async_setup_entry(hass, config_entry):
    """Set up the Transmission Component."""
    client = TransmissionClient(hass, config_entry)
    hass.data.setdefault(DOMAIN, {})[config_entry.entry_id] = client

    if not await client.async_setup():
        return False

    return True

async def async_unload_entry(hass, config_entry):
    """Unload Transmission Entry from config_entry."""
    client = hass.data[DOMAIN][config_entry.entry_id]
    hass.services.async_remove(DOMAIN, client.service_name)
    if client.unsub_timer:
        client.unsub_timer()

    for component in "sensor", "switch":
        await hass.config_entries.async_forward_entry_unload(config_entry, component)

    hass.data[DOMAIN].pop(config_entry.entry_id)

    return True

async def get_api(hass, entry):
    """Get Transmission client."""
    host = entry[CONF_HOST]
    port = entry[CONF_PORT]
    username = entry.get(CONF_USERNAME)
    password = entry.get(CONF_PASSWORD)

    try:
        api = await hass.async_add_executor_job(
            transmissionrpc.Client, host, port, username, password
        )
        _LOGGER.debug("Successfully connected to %s", host)
        return api

    except TransmissionError as error:
        if "401: Unauthorized" in str(error):
            _LOGGER.error("Credentials for Transmission client are not valid")
            raise AuthenticationError
        if "111: Connection refused" in str(error):
            _LOGGER.error("Connecting to the Transmission client %s failed", host)
            raise CannotConnect

        _LOGGER.error(error)
        raise UnknownError

class TransmissionClient:
    """Transmission Client Object."""

    def __init__(self, hass, config_entry):
        """Initialize the Transmission RPC API."""
        self.hass = hass
        self.config_entry = config_entry
        self._tm_data = None
        self.unsub_timer = None

    @property
    def service_name(self):
        """Return the service name."""
        return slugify(f"{SERVICE_ADD_TORRENT}_{self.config_entry.data[CONF_NAME]}")

    @property
    def api(self):
        """Return the tm_data object."""
        return self._tm_data

    async def async_setup(self):
        """Set up the Transmission client."""

        try:
            api = await get_api(self.hass, self.config_entry.data)
        except CannotConnect:
            raise ConfigEntryNotReady
        except (AuthenticationError, UnknownError):
            return False

        self._tm_data = TransmissionData(self.hass, self.config_entry, api)

        await self.hass.async_add_executor_job(self._tm_data.init_torrent_list)
        await self.hass.async_add_executor_job(self._tm_data.update)
        self.add_options()
        self.set_scan_interval(self.config_entry.options[CONF_SCAN_INTERVAL])

        for platform in ["sensor", "switch"]:
            self.hass.async_create_task(
                self.hass.config_entries.async_forward_entry_setup(
                    self.config_entry, platform
                )
            )

        def add_torrent(service):
            """Add new torrent to download."""
            torrent = service.data[ATTR_TORRENT]
            if torrent.startswith(
                ("http", "ftp:", "magnet:")
            ) or self.hass.config.is_allowed_path(torrent):
                api.add_torrent(torrent)
            else:
                _LOGGER.warning(
                    "Could not add torrent: unsupported type or no permission"
                )

        self.hass.services.async_register(
            DOMAIN, self.service_name, add_torrent, schema=SERVICE_ADD_TORRENT_SCHEMA
        )

        self.config_entry.add_update_listener(self.async_options_updated)

        return True

    def add_options(self):
        """Add options for entry."""
        if not self.config_entry.options:
            scan_interval = self.config_entry.data.pop(
                CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
            )
            options = {CONF_SCAN_INTERVAL: scan_interval}

            self.hass.config_entries.async_update_entry(
                self.config_entry, options=options
            )

    def set_scan_interval(self, scan_interval):
        """Update scan interval."""

        async def refresh(event_time):
            """Get the latest data from Transmission."""
            self._tm_data.update()

        if self.unsub_timer is not None:
            self.unsub_timer()
        self.unsub_timer = async_track_time_interval(
            self.hass, refresh, timedelta(seconds=scan_interval)
        )

    @staticmethod
    async def async_options_updated(hass, entry):
        """Triggered by config entry options updates."""
        hass.data[DOMAIN][entry.entry_id].set_scan_interval(
            entry.options[CONF_SCAN_INTERVAL]
        )

class TransmissionData:
    """Get the latest data and update the states."""

    def __init__(self, hass, config, api):
        """Initialize the Transmission RPC API."""
        self.hass = hass
        self.config = config
        self.data = None
        self.torrents = None
        self.session = None
        self.available = True
        self._api = api
        self.completed_torrents = []
        self.started_torrents = []
        self.started_torrent_dict = {}

    @property
    def host(self):
        """Return the host name."""
        return self.config.data[CONF_HOST]

    @property
    def signal_options_update(self):
        """Option update signal per transmission entry."""
        return f"tm-options-{self.host}"

    def update(self):
        """Get the latest data from Transmission instance."""
        try:
            self.data = self._api.session_stats()
            self.torrents = self._api.get_torrents()
            self.session = self._api.get_session()

            self.check_started_torrent_info()
            self.check_completed_torrent()
            self.check_started_torrent()
            _LOGGER.debug("Torrent Data for %s Updated", self.host)

            self.available = True
        except TransmissionError:
            self.available = False
            _LOGGER.error("Unable to connect to Transmission client %s", self.host)
        dispatcher_send(self.hass, self.signal_options_update)

    def init_torrent_list(self):
        """Initialize torrent lists."""
        self.torrents = self._api.get_torrents()
        self.completed_torrents = [
            x.name for x in self.torrents if x.status == "seeding"
        ]
        self.started_torrents = [
            x.name for x in self.torrents if x.status == "downloading"
        ]

    def check_completed_torrent(self):
        """Get completed torrent functionality."""
        actual_torrents = self.torrents
        actual_completed_torrents = [
            var.name for var in actual_torrents if var.status == "seeding"
        ]

        tmp_completed_torrents = list(
            set(actual_completed_torrents).difference(self.completed_torrents)
        )

        for var in tmp_completed_torrents:
            self.hass.bus.fire("transmission_downloaded_torrent", {"name": var})

        self.completed_torrents = actual_completed_torrents

    def check_started_torrent(self):
        """Get started torrent functionality."""
        actual_torrents = self.torrents
        actual_started_torrents = [
            var.name for var in actual_torrents if var.status == "downloading"
        ]

        tmp_started_torrents = list(
            set(actual_started_torrents).difference(self.started_torrents)
        )

        for var in tmp_started_torrents:
            self.hass.bus.fire("transmission_started_torrent", {"name": var})
        self.started_torrents = actual_started_torrents

    def check_started_torrent_info(self):
        """Get started torrent info functionality."""
        all_torrents = self._api.get_torrents()
        current_down = {}

        for torrent in all_torrents:
            if torrent.status == "downloading":
                info = self.started_torrent_dict[torrent.name] = {
                    "added_date": torrent.addedDate,
                    "percent_done": f"{torrent.percentDone * 100:.2f}",
                }
                try:
                    info["eta"] = str(torrent.eta)
                except ValueError:
                    info["eta"] = "unknown"

                current_down[torrent.name] = True

            elif torrent.name in self.started_torrent_dict:
                self.started_torrent_dict.pop(torrent.name)

        for torrent in list(self.started_torrent_dict):
            if torrent not in current_down:
                self.started_torrent_dict.pop(torrent)

    def get_started_torrent_count(self):
        """Get the number of started torrents."""
        return len(self.started_torrents)

    def get_completed_torrent_count(self):
        """Get the number of completed torrents."""
        return len(self.completed_torrents)

    def start_torrents(self):
        """Start all torrents."""
        self._api.start_all()

    def stop_torrents(self):
        """Stop all active torrents."""
        torrent_ids = [torrent.id for torrent in self.torrents]
        self._api.stop_torrent(torrent_ids)

    def set_alt_speed_enabled(self, is_enabled):
        """Set the alternative speed flag."""
        self._api.set_session(alt_speed_enabled=is_enabled)

    def get_alt_speed_enabled(self):
        """Get the alternative speed flag."""
        if self.session is None:
            return None

        return self.session.alt_speed_enabled


text:
<?php

namespace Krystal\Validate\Input\Constraint;

final class FileSize extends AbstractConstraint
{
    /**
     * {@inheritDoc}
     */
    protected $message = 'Given file path does not match required size';

    /**
     * Desired file size in bytes
     *
     * @var integer
     */
    private $size;

    /**
     * State initialization
     *
     * @param integer|float $size Size in bytes
     * @return void
     */
    public function __construct($size)
    {
        $this->size = $size;
    }

    /**
     * {@inheritDoc}
     */
    public function isValid($target)
    {
        if (filesize($target) == $this->size) {
            return true;
        } else {
            $this->violate($this->message);
            return false;
        }
    }
}


text:
require 'spec_helper'

describe Subscribem::Account do
  def schema_exists?(account)
    query = %Q{SELECT nspname FROM pg_namespace
               WHERE nspname='#{account.subdomain}'}
    result = ActiveRecord::Base.connection.select_value(query)
    result.present?
  end
  it "creates a schema" do
    account = Subscribem::Account.create!({
      :name => "First Account",
      :subdomain => "first"
    })
    account.create_schema
    failure_message = "Schema #{account.subdomain} does not exist"
    assert schema_exists?(account), failure_message
  end
end